【问题标题】:Customize WWW-Authenticate challenge header with Jwt Bearer Authentication middleware in WebAPI使用 WebAPI 中的 Jwt Bearer Authentication 中间件自定义 WWW-Authenticate 质询标头
【发布时间】:2023-03-24 01:20:01
【问题描述】:

我在 .NET WebAPI 项目中使用 JwtBearerAuthentication Katana 中间件通过 JWT 保护我的 Web API。

所以,在我的 Startup 课程中,我只是在做一些简单的事情,例如:

 app.UseJwtBearerAuthentication(
            new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                AllowedAudiences = new[] { audience },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                }
            });

一切都很好,只有一个例外。

当客户端传入无效或丢失的承载令牌时,WWW-Authenticate 响应标头只是“承载”。

我想自定义该标头以包含我的授权服务器的地址和支持的授权类型。

更像是:WWW-Authenticate: MyAuth href=url,grant_type="supported-grants" 或其他...

最好的方法是什么?我很惊讶 JwtBearerAuthenticationOptions 类不包含 Challenge 属性。我可以解决这个问题,但想知道 Jwt 中间件是否有最佳实践。

【问题讨论】:

    标签: asp.net-web-api asp.net-web-api2 identity jwt www-authenticate


    【解决方案1】:

    我们最终在 OAuthBearerAuthenticationProvider 中使用 OnApplyChallenge 插入了带有我们想要的值的 WWW-Authenticate 标头。

    类似的东西:

    app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions ...
       Provider = new OAuthBearerAuthenticationProvider()....
          OnApplyChallenge = (context) => context.OwinContext.Response.Headers.AppendValue(WWWAuthenticateHeader,values)
    

    【讨论】:

    • 比身份验证过滤器更好:您总是设置相同的挑战,因此您不需要实现过滤器的复杂性。挑战是在 oauth 中间件中设置的,而不是在 web api 中间件中
    猜你喜欢
    • 2018-04-15
    • 2023-03-20
    • 2021-10-21
    • 2021-09-03
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 2016-06-02
    相关资源
    最近更新 更多