我正在尝试使用oAuth 2.0中间件验证JWT。我尝试在Startup.cs类中使用自定义提供程序:
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
// Web API routes
config.MapHttpAttributeRoutes();
ConfigureOAuth(app);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
//For Dev enviroment only (on production should be AllowInsecureHttp = false)
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth2/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(5),
Provider = new CustomOAuthProvider(),
AccessTokenFormat = new RMAJwtAuthenticator.CustomJwtFormat("www.abc.com")
};
// OAuth 2.0 Bearer Access Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
// start : Code for Validating JWT
var issuer = "www.abc.com";
var audience = "www.xyz.com";
var secret = TextEncodings.Base64Url.Decode("Yuer534553HDS&dsa");
// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audience },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
},
Provider = new CustomOAuthBearerProvider()
});
//End: Code for Validating JWT
}
}
在我的CustomOAuthBearerProvider中,它继承了IOAuthBearerAuthenticationProvider,我提供了ApplyChallenge()、RequestToken()和ValidateIdentity()的定义:
public class CustomOAuthBearerProvider : IOAuthBearerAuthenticationProvider
{
public Task ApplyChallenge(OAuthChallengeContext context)
{
return Task.FromResult<object>(null);
}
public Task RequestToken(OAuthRequestTokenContext context)
{
return Task.FromResult<object>(null);
}
public Task ValidateIdentity(OAuthValidateIdentityContext context)
{
return Task.FromResult<object>(null);
}
}
现在,当我尝试获取授权资源时,首先会触发RequestToken()方法,然后我不知道JWT是如何验证的并且控制权被传递给ValidateIdentity()方法。
我想自定义验证过程的原因是为了在数据库中保存和扩展我的JWT的过期时间(您也可以建议任何增加JWT过期时间而不更改原始令牌的方法)。
请评论任何有用的思路/建议/良好-不良做法选项/链接,谢谢。