How to Customize ASP.NET Web API AuthorizeAttribute for Unusual Requirements

前端 未结 3 1046
我寻月下人不归
我寻月下人不归 2020-11-29 00:30

I am inheriting from System.Web.Http.AuthorizeAttribute to create a custom authorization/authentication routine to meet some unusual requirements for a web

3条回答
  •  迷失自我
    2020-11-29 01:12

    To add to the absolutely correct answer by Kevin, I'd like to say that I may slightly modify it to leverage the existing .NET framework path for the response object to ensure downstream code in the framework (or other consumers) is not adversely affected by some weird idiosyncrasy that can't be predicted.

    Specifically this means using this code:

    actionContext.Response = actionContext.ControllerContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, REQUEST_NOT_AUTHORIZED);
    

    rather than:

    actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
    

    Where REQUEST_NOT_AUTHORIZED is:

    private const string REQUEST_NOT_AUTHORIZED = "Authorization has been denied for this request.";
    

    I pulled that string from the SRResources.RequestNotAuthorized definition in the .NET framework.

    Great answer Kevin! I implemented mine the very same way because executing OnAuthorization in the base class made no sense because I was verifying an HTTP Header that was custom to our application and didn't actually want to check the Principal at all because there wasn't one.

提交回复
热议问题