ASP.NET web api - Set custom IIdentity or IPrincipal

后端 未结 4 1460
醉梦人生
醉梦人生 2021-02-09 06:49

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 06:57

    This AuthorizeAttribute implementation worked for me. It's designed for Http Basic Auth but obviously I want to get the User.Identity.IsAuthenticated and User.Identity.Name from inside a ApiController too and this works:

    public class ApiAuthAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var session = (ISession)actionContext.Request.GetDependencyScope().GetService(typeof(ISession));
    
            if (actionContext.Request.Headers.Authorization != null)
            {
                var authConcat = Encoding.UTF8.GetString(Convert.FromBase64String(actionContext.Request.Headers.Authorization.Parameter));
                var email = authConcat.Split(':')[0];
                var password = authConcat.Split(':')[1];
    
                var user = session.Query().SingleOrDefault(u => u.Email == email);
                if (user != null && user.IsAuthenticated(password))
                {
                    actionContext.ControllerContext.RequestContext.Principal = new GenericPrincipal(new GenericIdentity(user.Email), new string[] { });
                    return;     // and continue with controller
                }
            }
    
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.NotFound);
        }
    }
    

提交回复
热议问题