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

C# 如何在OWIN中间件中捕获SecurityTokenExpiredException?,c#,.net,owin,.net-framework-version,refresh-token,C#,.net,Owin,.net Framework Version,Refresh Token,我有一个带有OWIN的Web API,它使用JWTBeareAuthenticationOptions(.Net Framework 4.5.2)来验证身份验证令牌 虽然Rui Figueiredo为了向API添加刷新令牌功能,但似乎在OWIN中没有JwtBearerEvents。例如,此代码在ASP.NET Core(在ConfigureServices中)中适用: 我似乎无法理解如何使用OWIN管道实现同样的效果。我尝试在ConfigureAuth中插入一个中间件: private stat

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

虽然Rui Figueiredo为了向API添加刷新令牌功能,但似乎在OWIN中没有
JwtBearerEvents
。例如,此代码在ASP.NET Core(在ConfigureServices中)中适用:

我似乎无法理解如何使用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状态没有令牌过期标头


有人对如何在卡塔纳正确地做到这一点有什么建议吗?

解决了这个问题。在的领导下,我向我的基本控制器添加了一个自定义授权属性,即:

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;
}
public bool令牌已过期(字符串令牌字符串)
{
var token=ReadToken(tokenString);
var haseexpired=token.ValidTo

public bool TokenHasExpired(string tokenString)
{
    var token = ReadToken(tokenString);
    var hasExpired = token.ValidTo < DateTime.UtcNow;
    return hasExpired;
}