ASP.NET web api - Set custom IIdentity or IPrincipal

后端 未结 4 1137
忘掉有多难
忘掉有多难 2021-02-09 06:29

In our asp.net mvc/web api project, we want to customize the authorization using AuthorizeAttribute. We have noticed that there are two different AuthorizeAtt

4条回答
  •  孤街浪徒
    2021-02-09 07:01

    Just extend your IPrincipal.

    public static class IPrincipalExtension
    {
       public static bool IsValid(this IPrincipal p)
       {
           // your custom validation
           return true;
       }
    }
    

    Now reference your namespace and use like this.

    public class MyAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
    {
        protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var valid = actionContext.RequestContext.Principal.IsValid(); // this will return boolean
            // your code here
    
    
        }
    }
    

提交回复
热议问题