ASP.NET Web API OAUTH2自定义401未经授权的响应



我正在使用microsoft.owin.security.jwt。我的资源服务器配置如下:

// Resource server configuration
var audience = "hello";
var secret = TextEncodings.Base64Url.Decode("world);
// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(
    new JwtBearerAuthenticationOptions
    {
        AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
        AllowedAudiences = new[] { audience },
        IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
        {
            new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
        }
    });

当前,当令牌过期时,响应如下:

401 Unauthorized
**Headers:**
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/10.0
Www-Authenticate: Bearer
X-Sourcefiles: =?UTF-8?B?Yzpcc3JjXFVTQi5FbnRlcnByaXNlQXV0b21hdGlvbi5BdXRoQXBpXFVTQi5FbnRlcnByaXNlQXV0b21hdGlvbi5BdXRoQXBpXGFwaVx1c2VyXGxvb2t1cFxsaWtvc3Rv?=
X-Powered-By: ASP.NET
Date: Fri, 30 Dec 2016 13:54:26 GMT
Content-Length: 61

身体

{
"message": "Authorization has been denied for this request."
}

是否有一种方法可以设置自定义www-partenticate标头,并且如果令牌过期,/或添加到身体?

我想返回以下内容:

WWW-Authenticate: Bearer realm="example", 
    error="invalid_token", 
    error_description="The access token expired"

做到这一点的一种方法是创建自定义AuthorizeAttribute,然后装饰所讨论的方法或类。确保覆盖HandleUnauthorizedRequest,然后调用其base方法以正常运行并返回401

public class CustomAuthorize : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        HttpContext.Current.Response.AppendHeader("WWW-Authenticate", @"Bearer realm=""example"" ... ");
        base.HandleUnauthorizedRequest(actionContext);
    }
}

用法:

[CustomAuthorize]
public IHttpActionResult Get()
{
    ...
}

可能需要在标题周围进行一些进一步的逻辑,但应该足以开始。

最新更新