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

ASP.NET Web API OAuth2自定义401未经授权的响应,asp.net,asp.net-web-api,oauth-2.0,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.UseJwtBearerA

我正在使用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
当前,当令牌过期时,响应如下:

// 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
身体

是否有办法设置自定义Www身份验证标头,和/或在令牌过期时添加到正文中

我想退货,比如:

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()
{
    ...
}
可能需要一些关于标题的进一步逻辑,但应该足以开始使用