我创建了一个后端WebApi来创建JWT令牌,当我使用PostMan通过将标记添加到标题来访问受限资源时,它们正常工作,例如[授权(角色="超级管理员&#34)]。
我想在我的MVC应用程序中使用此基础架构,但不太知道如何将它绑在一起。
我猜测当用户创建一个帐户并为他们生成JWT时(通过WebApi),我需要将令牌粘贴在cookie中,但是如何做到这一点并从中提取JWT关于未来请求的cookie,以便它可以使用我用ActionResults装饰的普通[Authorize]属性吗?
我是否需要在Owin管道中放置一些东西? 或者我是否需要创建自定义[授权]属性?
我的Startup.cs文件目前看起来像这样:
public void Configuration(IAppBuilder app)
{
HttpConfiguration httpConfig = new HttpConfiguration();
ConfigureOAuthTokenGeneration(app);
ConfigureOAuthTokenConsumption(app);
ConfigureWebApi(httpConfig);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(httpConfig);
}
private void ConfigureOAuthTokenGeneration(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
//TODO: enforce https in live
//For Dev enviroment only (on production should be AllowInsecureHttp = false)
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new CustomOAuthProvider(),
AccessTokenFormat = new CustomJwtFormat("https://localhost:443")
};
// Plugin the OAuth bearer JSON Web Token tokens generation and Consumption will be here
// OAuth 2.0 Bearer Access Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
}
private void ConfigureOAuthTokenConsumption(IAppBuilder app)
{
var issuer = "https://localhost:443";
string audienceId = ConfigurationManager.AppSettings["as:AudienceId"];
byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:AudienceSecret"]);
// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audienceId },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
}
});
}
private void ConfigureWebApi(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
如果有帮助,我正在遵循本指南: http://bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in-asp-net-web-api-and-identity-2/
答案 0 :(得分:2)
您引用的基础架构实际上是为处理直接Web API调用而设计的。基于经典重定向的Web应用程序将依赖于更传统的模式,其中应用程序接收一个令牌,验证它并使用它来启动经过身份验证的会话(通过在某些会话工件中保存令牌验证的结果,如令牌)。虽然您可以从任何基于令牌的系统(包括自定义系统)开始实施此模式,但通常利用现有协议(如OpenId Connect)和现有产品(如Azure AD或Identity Server)更方便(且更安全)。有关基于Azure AD的简单示例,请参阅this - 无论您选择哪种OpenId提供程序,中间件都保持不变。