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

时间:2016-12-30 14:19:51

标签: asp.net asp.net-web-api oauth-2.0

我使用的是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-Authenticate标头,和/或在令牌过期时添加到正文?

我想返回类似的内容:

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

1 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是创建自定义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()
{
    ...
}

可能需要一些关于标题的进一步逻辑,但应该足以开始使用。