blgrnboy
blgrnboy

Reputation: 5167

ASP.NET Web API OAuth2 customize 401 unauthorized response

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"

Upvotes: 2

Views: 889

Answers (1)

G0dsquad
G0dsquad

Reputation: 4435

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.

Upvotes: 1

Related Questions