In my WebAPI project, I have number of apis which are decorated with [Authorize]
attribute.
[Authorize] public HttpResponseMessage GetCustomers() { //my api }
In case user doesn't have the right token, an access denied exception is returned to the user.
But what I need is that in any such case, I need to return the custom response message as.
{ "StatusCode" : 403, "message": "You donot have sufficient permission" }
How do I return this custom message in case authorization fails.
Please note:
To implement a custom authorization filter, we need to create a class that derives either AuthorizeAttribute , AuthorizationFilterAttribute , or IAuthorizationFilter . AuthorizeAttribute : An action is authorized based on the current user and the user's roles.
One of the new features in ASP.NET MVC 4 is the AllowAnonymous Attribute that helps you secure an entire ASP.NET MVC 4 Website or Controller while providing a convenient means of allowing anonymous users access to certain controller actions, like the login and register Actions.
There are different ways to do this but one of the best way could be custom authorization attributes.You just need to inherit the AuthorizeAttribute
and override HandleUnauthorizedRequest()
method of it.
public class CustomAuthorization : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) { actionContext.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent("You are unauthorized to access this resource") }; } }
and use this like(CustomAuthorization
should be used in-place of Authorize
)
[CustomAuthorization] public IHttpActionResult Get() { return Ok(); }
Otherwise you can also catch the status code in client side and display the custom message of your choice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With