Question: ASP.NET Web API OAuth2 customize 401 unauthorized response

Question

ASP.NET Web API OAuth2 customize 401 unauthorized response

Answers 1
Added at 2016-12-30 15:12
Tags
Question

I am using Microsoft.Owin.Security.Jwt. My resource server is configured as follows:

// 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)
        }
    });

Currently, when a token is expired, the Reponse is as follows:

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

Body

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

Is there a way to set a custom Www-Authenticate header, and/or add to the body if the token is expired?

I'd like to return something like:

WWW-Authenticate: Bearer realm="example", 
    error="invalid_token", 
    error_description="The access token expired"
Answers
nr: #1 dodano: 2016-12-30 17:12

One way to do this is to create a custom AuthorizeAttribute and then decorate the method or class in question. Make sure to override HandleUnauthorizedRequest and then call its base method to carry on as normal and return 401.

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

Usage:

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

May need some further logic around headers but should be enough to get started with.

Source Show
◀ Wstecz