我有一个带有OWIN的Web API,它使用JwtBearerAuthenticationOptions
(.NET Framework 4.5.2)验证身份验证令牌。
在关注Rui Figueiredo的这篇出色文章以便为API添加刷新功能时,我似乎在OWIN中没有JwtBearerEvents
。例如。此代码在ASP.NET Core(在Configureservices中)中适用于我:
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = GetDefaultValidationParameters();
x.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
});
我似乎无法使用OWIN管道来掌握如何实现相同的方法。我尝试的是在configureauth中插入中间件:
private static void ConfigureAuth(IAppBuilder pApp)
{
pApp.Use(async (context, next) =>
{
try
{
await next.Invoke();
}
catch (SecurityTokenExpiredException)
{
context.Response.Headers.Add("Token - Expired", new[] { "true" });
throw;
}
});
var issuer = "issuer";
var audience = "all";
var key = Encoding.ASCII.GetBytes("MySecretKey");
pApp.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
AllowedAudiences = new[] { audience },
IssuerSecurityKeyProviders = new IIssuerSecurityKeyProvider[]
{
new SymmetricKeyIssuerSecurityKeyProvider(issuer, key)
},
TokenValidationParameters = tokenValidationParameters,
TokenHandler = new CustomJWTTokenHandler()
});
}
,但无济于事。在这种情况下,401状态无需代币便度。
有人在Katana中正确执行此操作吗?
解决了它。遵循这些答案的领导,我在基本控制器中添加了自定义授权属性,即:
public class CustomAuthorization : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
base.HandleUnauthorizedRequest(actionContext);
var ctx = actionContext;
var token = ctx.Request.Headers.Authorization.Parameter;
var handler = new CustomJWTTokenHandler();
if (ctx.Response.StatusCode == HttpStatusCode.Unauthorized && handler.TokenHasExpired(token))
{
ctx.Response.Headers.Add("Token-Expired", "true");
}
}
}
并在我的CustomJWTTokenHandler
类中实现了到期检查:
public bool TokenHasExpired(string tokenString)
{
var token = ReadToken(tokenString);
var hasExpired = token.ValidTo < DateTime.UtcNow;
return hasExpired;
}
hth