如何在OWIN中间件中捕获SecurityTokenExpiredException?

问题描述 投票:1回答:1

我有一个带有OWIN的Web API,它使用JwtBearerAuthenticationOptions(.Net Framework 4.5.2)来验证身份验证令牌。

在遵循Rui Figueiredo的this excellent article以便为API添加Refresh Token功能的同时,似乎我在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状态没有Token-Expired标头。

有没有人在Katana中有任何关于如何正确做到这一点的指示?

c# .net owin .net-framework-version refresh-token
1个回答
2
投票

解决了它。在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

© www.soinside.com 2019 - 2024. All rights reserved.