I'm doing an API Rest in an MVC project. In the API controllers ( ApiController
) I place the DataAnnotation Authorize
, when the token entered is invalid, it detects and tries to redirect to the login page. But I do not want this behavior in Api, I want to return a 401 error, if possible with a JSON object stating that the user is not allowed to access the content.
[WebApiAuthorize(Roles = Constantes.PERMISSAO_API)]
[RoutePrefix("api/v1/controller")]
public class BancoController : ApiController {
}
This is the custom Authorize class
public class WebApiAuthorizeAttribute : AuthorizeAttribute {
protected override void HandleUnauthorizedRequest(HttpActionContext ctx) {
if (!ctx.RequestContext.Principal.Identity.IsAuthenticated) {
ctx.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
} else {
ctx.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
}
}
}