我有一个带有OWIN的Web API,它使用JwtBearerAuthenticationOptions
(.Net Framework4.5.2)来验证身份验证令牌。
在遵循Rui Figueiredo的this excellent article以便向API添加刷新令牌功能时,我似乎在OWIN中没有JwtBearerEvents
。例如,这段代码适用于我在ASP.NET核心中(在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状态没有Token-Expired报头。
有谁对如何在Katana中正确地做到这一点有什么建议吗?
发布于 2019-03-15 23:17:04
解决了它。在these answers之后,我在我的基本控制器中添加了一个自定义授权属性,即:
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
https://stackoverflow.com/questions/55171209
复制相似问题