Make Web API authentication return 401 instead of redirect to login page

前端 未结 6 1128
孤城傲影
孤城傲影 2021-01-04 00:58

I have Web API with OWIN Authentication in Web MVC. I\'m using in Web.Config for my Web MVC so it\'s redirecting to login page.



        
6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-04 01:16

    This is what worked for me.

    Creating a custom attribute:

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class NoRedirectAuthorizeAttribute : AuthorizeAttribute
    {        
        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
        }
    }
    

    Using the attribute in your controller:

        [HttpDelete]
        [NoRedirectAuthorizeAttribute(Roles = "Admin")]
        [Route("api/v3/thingstodelete/{id=id}")]
        public IHttpActionResult DeleteThingToDelete(Guid id)
        {
          //delete code
        }
    

    Here are just overriding the HandleUnauthorizedRequest method of the AuthorizeAttribute. So, instead of sending a redirect (304) to the login page, we send Forbidden(403) HTTP status code.

提交回复
热议问题