将 OAuth 不记名令牌 (JWT) 与 MVC 结合使用
Using An OAuth Bearer Token (JWT) With MVC
我创建了一个后端 WebApi 来创建 JWT 令牌,当我使用 PostMan 通过将令牌添加到 header 来访问受限资源时,它们工作正常,例如[授权(角色="SuperAdmin")].
我想在我的 MVC 应用程序中使用此基础结构,但不太清楚如何将它们结合在一起。
我猜想当用户创建一个帐户并且我为他们生成一个 JWT(通过 WebApi)时,我需要将令牌粘贴到 cookie 中,但是如何做到这一点并从中提取 JWT cookie 在未来的请求中,以便它可以与我装饰 ActionResults 的正常 [Authorize] 属性一起使用?
我需要在 Owin 管道中添加一些东西吗?
或者我是否需要创建自定义 [Authorize] 属性?
我的 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/
您提到的基础设施实际上是为处理直接网络 API 调用而设计的。经典的基于重定向的 Web 应用程序会退回到更传统的模式,其中应用程序接收一个令牌,对其进行验证并使用它来启动经过身份验证的会话(通过将令牌验证的结果保存在某些会话工件中,例如令牌)。尽管您可以从任何基于令牌的系统(包括您的自定义系统)开始实施此模式,但通常利用现有协议(如 OpenId Connect)和现有产品(如 Azure AD 或 Identity Server). See this for a基于 Azure AD 的简单示例 - 无论您选择什么 OpenId 提供商,中间件都保持不变。
我创建了一个后端 WebApi 来创建 JWT 令牌,当我使用 PostMan 通过将令牌添加到 header 来访问受限资源时,它们工作正常,例如[授权(角色="SuperAdmin")].
我想在我的 MVC 应用程序中使用此基础结构,但不太清楚如何将它们结合在一起。
我猜想当用户创建一个帐户并且我为他们生成一个 JWT(通过 WebApi)时,我需要将令牌粘贴到 cookie 中,但是如何做到这一点并从中提取 JWT cookie 在未来的请求中,以便它可以与我装饰 ActionResults 的正常 [Authorize] 属性一起使用?
我需要在 Owin 管道中添加一些东西吗? 或者我是否需要创建自定义 [Authorize] 属性?
我的 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/
您提到的基础设施实际上是为处理直接网络 API 调用而设计的。经典的基于重定向的 Web 应用程序会退回到更传统的模式,其中应用程序接收一个令牌,对其进行验证并使用它来启动经过身份验证的会话(通过将令牌验证的结果保存在某些会话工件中,例如令牌)。尽管您可以从任何基于令牌的系统(包括您的自定义系统)开始实施此模式,但通常利用现有协议(如 OpenId Connect)和现有产品(如 Azure AD 或 Identity Server). See this for a基于 Azure AD 的简单示例 - 无论您选择什么 OpenId 提供商,中间件都保持不变。