2016-12-30 85 views
2

我正在使用Microsoft.Owin.Security.Jwt。我的资源服务器配置如下:ASP.NET Web API OAuth2定制401未授权响应

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

的一种方式做,这是创建一个自定义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() 
{ 
    ... 
} 

可能需要大约标题一些进一步的逻辑,但应足够上手。