Web api 2 within MVC project. How to prevent redirection to login page when token is not valid

Asked

Viewed 96 times

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);
        }
    }
}

1 answer

0

Hello, try using Result to return to your desired status.

public class WebApiAuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAuthenticated)
        {
            filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult(HttpStatusCode.Unauthorized);
        }
        else
        {
           base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.