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

前端 未结 3 1042
我寻月下人不归
我寻月下人不归 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:01

    The best solution for my scenario appears to be bypass the base OnAuthorization completely. Since I have to authenticate each time cookies and caching the principle are not of much use. So here is the solution I came up with:

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        string username;
        string password;
    
        if (GetUserNameAndPassword(actionContext, out username, out password))
        {
            if (Membership.ValidateUser(username, password))
            {
                if (!isUserAuthorized(username))
                    actionContext.Response = 
                        new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
            }
            else
            {
                actionContext.Response = 
                    new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
            }
        }
        else
        {
            actionContext.Response = 
                new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
        }
    }
    

    I developed my own method for validating the roles called isUserAuthorized and I am not using the base OnAuthorization any more since it checks the current Principle to see if it isAuthenticated. IsAuthenticated only allows gets so I am not sure how else to set it, and I do not seem to need the current Principle. Tested this out and it works fine.

    Still interested if anyone has a better solution or can see any issues with this this one.

提交回复
热议问题