0
I’m doing a Rest API on an MVC project. On the API controllers (ApiController) place the Dataannotation Authorize, when the token entered is invalid, it detects and tries to redirect to the login page. Only I don’t want this behavior in the Api, I want to return a 401 error, if possible with a JSON object stating that the user is not authorized to access the content.
[WebApiAuthorize(Roles = Constantes.PERMISSAO_API)]
[RoutePrefix("api/v1/controller")]
public class BancoController : ApiController {
}
This is the custom class of Authorize
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);
}
}
}