简体   繁体   中英

How to Modify “Authorization has been denied for this request.” Using filter HostAuthenticationFilter

Using Bearer token authentication. If response is failure then, need to return additional field along with below message:

401 UnAuthorize response
{Message: "Authorization has been denied for this request"}

How to include additional field in 401 response message. It will be like as below: (include additional field 'ID' that indicate failure tracking ID).

{Message: "Authorization has been denied for this request",
 Id: 1}

filter.config is below:

config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

You need to provide your own implementation the authorization attributes by overriding AuthorizeAttribute.

public class YourCustomAuthorization : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        actionContext.Response = new HttpResponseMessage
        {
            StatusCode = HttpStatusCode.Unauthorized,
            Content = new StringContent("You Message")
        };
    }
}

and use it as

[CustomAuthorization]       
public IHttpActionResult Get()
{
    return Ok();
}

Also check this: http://prideparrot.com/blog/archive/2012/6/customizing_authorize_attribute

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM