【发布时间】:2015-09-15 08:40:17
【问题描述】:
我有一个使用 UseJwtBearerAuthentication 到我的身份服务器的 Web API 项目。 启动时的配置方法如下:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseJwtBearerAuthentication(options =>
{
options.AutomaticAuthentication = true;
options.Authority = "http://localhost:54540/";
options.Audience = "http://localhost:54540/";
});
// Configure the HTTP request pipeline.
app.UseStaticFiles();
// Add MVC to the request pipeline.
app.UseMvc();
}
这是可行的,我想在 MVC5 项目中做同样的事情。我试图做这样的事情:
网页接口:
public class SecuredController : ApiController
{
[HttpGet]
[Authorize]
public IEnumerable<Tuple<string, string>> Get()
{
var claimsList = new List<Tuple<string, string>>();
var identity = (ClaimsIdentity)User.Identity;
foreach (var claim in identity.Claims)
{
claimsList.Add(new Tuple<string, string>(claim.Type, claim.Value));
}
claimsList.Add(new Tuple<string, string>("aaa", "bbb"));
return claimsList;
}
}
如果设置属性 [授权],我无法调用 web api(如果我删除它,它就可以工作)
我创建了 Startup。这段代码永远不会被调用,我不知道要改变什么才能让它工作。
[assembly: OwinStartup(typeof(ProAuth.Mvc5WebApi.Startup))]
namespace ProAuth.Mvc5WebApi
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureOAuth(app);
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
Uri uri= new Uri("http://localhost:54540/");
PathString path= PathString.FromUriComponent(uri);
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = path,
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
context.Validated(identity);
}
}
}
目标是将声明从 Web api 返回到客户端应用程序。使用承载认证。
感谢您的帮助。
【问题讨论】:
-
在哪里可以找到 app.UseJwtBearerAuthentication(...) ?您的 project.json 和使用引用(在 Startup.cs 上)是什么样的?
-
"Microsoft.AspNet.Authentication.JwtBearer":"1.0.0-*"
-
在未调用您的启动代码时,您可能需要一组符合 MVC5 的 nuget 依赖项。我只是使用 Global.asax.cs
Application_Start方法而不是OwinStartup -
你安装了web主机包吗? Microsoft.Owin.Host.SystemWeb 是必需的 - 例如stackoverflow.com/questions/20203982/owinstartup-not-firing
-
看起来问题已经完全改变了......你能粘贴你的 WebApiConfig 类吗?
标签: c# authentication asp.net-web-api asp.net-mvc-5 asp.net-core-mvc