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

0

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);
        }
    }
}
    
asked by anonymous 02.02.2017 / 21:05

1 answer

0

Hello, try using Result to return to the 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);
        }
    }
}
    
02.03.2017 / 17:27