Custom RoleProvider failing when AuthorizeAttribut

2019-04-14 01:26发布

问题:

I'm having an issue with a custom role provider in ASP.net MVC4. I implemented a very light weight RoleProvider which seems to work fine right up until I change

[Authorize]
public class BlahController:....
}

to

[Authorize(Roles="Administrator")]
public class BlahController:....
}

as soon as I make that change users are no longer authenticated and I get 401 errors. This is odd because my RoleProvider basically returns true for IsUSerInRole and a list containing "Administrator" for GetUserRoles. I had breakpoints in place on every method in my custom RoleProvider and found that none of them were being called.

Next I implemented my own authorize attribute which inherited from AuthorizeAttribute. In this I put in break points so I could see what was going on. It turned out that User.IsInRole(), which is called by the underlying attribute was returning false.

I am confident that the role provider is properly set up. I have this in my config file

<roleManager enabled="true" defaultProvider="SimplicityRoleProvider">
  <providers>
    <clear />
    <add name="SimplicityRoleProvider" type="Simplicity.Authentication.SimplicityRoleProvider" applicationName="Simplicity" />
  </providers>
</roleManager>

and checking which role provider is the current one using the method described here: Reference current RoleProvider instance? yields the correct result. However User.IsInRole persists in returning false.

I am using Azure Access Control Services but I don't see how that would be incompatible with a custom role provider.

What can I do to correct the IPrincipal User such that IsInRole returns the value from my custom RoleProvider?


RoleProvider source:

public class SimplicityRoleProvider : RoleProvider { private ILog log { get; set; }

    public SimplicityRoleProvider()
    {
        log = LogManager.GetLogger("ff");
    }        

    public override void AddUsersToRoles(string[] usernames, string[] roleNames)
    {
        log.Warn(usernames);
        log.Warn(roleNames);
    }

    public override string ApplicationName
    {
        get
        {
            return "Simplicity";
        }
        set
        {

        }
    }

    public override void CreateRole(string roleName)
    {

    }

    public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
    {
        return true;
    }

    public override string[] FindUsersInRole(string roleName, string usernameToMatch)
    {
        log.Warn(roleName);
        log.Warn(usernameToMatch);
        return new string[0];
    }

    public override string[] GetAllRoles()
    {
        log.Warn("all roles");
        return new string[0];
    }

    public override string[] GetRolesForUser(string username)
    {
        log.Warn(username);
        return new String[] { "Administrator" };
    }

    public override string[] GetUsersInRole(string roleName)
    {
        log.Warn(roleName);
        return new string[0];
    }

    public override bool IsUserInRole(string username, string roleName)
    {
        log.Warn(username);
        log.Warn(roleName);
        return true;
    }

    public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
    {

    }

    public override bool RoleExists(string roleName)
    {
        log.Warn(roleName);
        return true;
    }
}

回答1:

It seems that System.Web.Security.Roles.GetRolesForUser(Username) does not get automatically hooked up when you have a custom AuthorizeAttribute and a custom RoleProvider.

So, in your custom AuthorizeAttribute you need to retrieve the list of roles from your data source and then compare them against the roles passed in as parameters to the AuthorizeAttribute.

I have seen in a couple blog posts comments that imply manually comparing roles is not necessary but when we override AuthorizeAttribute it seems that we are suppressing this behavior and need to provide it ourselves.


Anyway, I'll walk through what worked for me. Hopefully it will be of some assistance.

I welcome comments on whether there is a better way to accomplish this.

Note that in my case the AuthorizeAttribute is being applied to an ApiController although I'm not sure that is a relevant piece of information.

   public class RequestHashAuthorizeAttribute : AuthorizeAttribute
    {
        bool requireSsl = true;

        public bool RequireSsl
        {
            get { return requireSsl; }
            set { requireSsl = value; }
        }

        bool requireAuthentication = true;

        public bool RequireAuthentication
        {
            get { return requireAuthentication; }
            set { requireAuthentication = value; }
        }

        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext ActionContext)
        {
            if (Authenticate(ActionContext) || !RequireAuthentication)
            {
                return;
            }
            else
            {
                HandleUnauthorizedRequest(ActionContext);
            }
        }

        protected override void HandleUnauthorizedRequest(HttpActionContext ActionContext)
        {
            var challengeMessage = new System.Net.Http.HttpResponseMessage(HttpStatusCode.Unauthorized);
            challengeMessage.Headers.Add("WWW-Authenticate", "Basic");
            throw new HttpResponseException(challengeMessage);
        }

        private bool Authenticate(System.Web.Http.Controllers.HttpActionContext ActionContext)
        {
            if (RequireSsl && !HttpContext.Current.Request.IsSecureConnection && !HttpContext.Current.Request.IsLocal)
            {
                //TODO: Return false to require SSL in production - disabled for testing before cert is purchased
                //return false;
            }

            if (!HttpContext.Current.Request.Headers.AllKeys.Contains("Authorization")) return false;

            string authHeader = HttpContext.Current.Request.Headers["Authorization"];

            IPrincipal principal;
            if (TryGetPrincipal(authHeader, out principal))
            {
                HttpContext.Current.User = principal;
                return true;
            }
            return false;
        }

        private bool TryGetPrincipal(string AuthHeader, out IPrincipal Principal)
        {
            var creds = ParseAuthHeader(AuthHeader);
            if (creds != null)
            {
                if (TryGetPrincipal(creds[0], creds[1], creds[2], out Principal)) return true;
            }

            Principal = null;
            return false;
        }

        private string[] ParseAuthHeader(string authHeader)
        {
            if (authHeader == null || authHeader.Length == 0 || !authHeader.StartsWith("Basic")) return null;

            string base64Credentials = authHeader.Substring(6);
            string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(base64Credentials)).Split(new char[] { ':' });

            if (credentials.Length != 3 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[1]) || string.IsNullOrEmpty(credentials[2])) return null;

            return credentials;
        }

        private bool TryGetPrincipal(string Username, string ApiKey, string RequestHash, out IPrincipal Principal)
        {
            Username = Username.Trim();
            ApiKey = ApiKey.Trim();
            RequestHash = RequestHash.Trim();

            //is valid username?
            IUserRepository userRepository = new UserRepository();
            UserModel user = null;
            try
            {
                user = userRepository.GetUserByUsername(Username);
            }
            catch (UserNotFoundException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }

            //is valid apikey?
            IApiRepository apiRepository = new ApiRepository();
            ApiModel api = null;
            try
            {
                api = apiRepository.GetApi(new Guid(ApiKey));
            }
            catch (ApiNotFoundException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }

            if (user != null)
            {
                //check if in allowed role
                bool isAllowedRole = false;
                string[] userRoles = System.Web.Security.Roles.GetRolesForUser(user.Username);
                string[] allowedRoles = Roles.Split(',');  //Roles is the inherited AuthorizeAttribute.Roles member
                foreach(string userRole in userRoles)
                {
                    foreach (string allowedRole in allowedRoles)
                    {
                        if (userRole == allowedRole)
                        {
                            isAllowedRole = true;
                        }
                    }
                }

                if (!isAllowedRole)
                {
                    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
                }

                Principal = new GenericPrincipal(new GenericIdentity(user.Username), userRoles);                
                Thread.CurrentPrincipal = Principal;

                return true;
            }
            else
            {
                Principal = null;
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }
        }
    }

The custom authorize attribute is governing the following controller:

public class RequestKeyAuthorizeTestController : ApiController
{
    [RequestKeyAuthorizeAttribute(Roles="Admin,Bob,Administrator,Clue")]
    public HttpResponseMessage Get()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "RequestKeyAuthorizeTestController");
    }
}

In the custom RoleProvider, I have this method:

public override string[] GetRolesForUser(string Username)
{
    IRoleRepository roleRepository = new RoleRepository();
    RoleModel[] roleModels = roleRepository.GetRolesForUser(Username);

    List<string> roles = new List<string>();

    foreach (RoleModel roleModel in roleModels)
    {
        roles.Add(roleModel.Name);
    }

    return roles.ToArray<string>();
}


回答2:

So the issue is not how you implement the role provider, but rather how you configure your application to use it. I could not find any issues in your configuration, though. Please make sure this is indeed how you configure your application. This post may help: http://brianlegg.com/post/2011/05/09/Implementing-your-own-RoleProvider-and-MembershipProvider-in-MVC-3.aspx. If you use the default MVC template to create the project, please check the AccountController. According to that post, you may need to do a few modifications to make a custom membership provider work. But that would not affect role providers.

Best Regards,

Ming Xu.



回答3:

I don't like the custom authorization attribute because I have to remind people to use it. I chose to implement the my own IIdentity/IPrincipal class and wire it up on authorization.

The custom UserIdentity that calls the default RoleProvider:

public class UserIdentity : IIdentity, IPrincipal
{
    private readonly IPrincipal _original;

    public UserIdentity(IPrincipal original){
        _original = original;
    }

    public string UserId
    {
        get
        {
            return _original.Identity.Name;
        }
    }

    public string AuthenticationType
    {
        get
        {
            return _original.Identity.AuthenticationType;
        }
    }

    public bool IsAuthenticated
    {
        get
        {
            return _original.Identity.IsAuthenticated;
        }
    }

    public string Name
    {
        get
        {
            return _original.Identity.Name;
        }
    }

    public IIdentity Identity
    {
        get
        {
            return this;
        }
    }

    public bool IsInRole(string role){
        return Roles.IsUserInRole(role);
    }
}

and added this to global.asax.cs:

void Application_PostAuthenticateRequest(object sender, EventArgs e)
{                                   
    if(false == HttpContext.Current.User is UserIdentity){
        HttpContext.Current.User = new UserIdentity(HttpContext.Current.User);
    }
}


回答4:

What stimms wrote in his comment: "What I'm seeing is that the IPrincipal doesn't seem to have the correct RoleProvider set" got me looking at the implementation of my custom authentication attribute which inherits from Attribute and IAuthenticationFilter.

using System.Web.Security;

....

protected override async Task<IPrincipal> AuthenticateAsync(string userName, string password, CancellationToken cancellationToken)
{
    if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
    {
        // No user with userName/password exists.
        return null;
    }

    var membershipProvider = Membership.Providers["CustomMembershipProvider"];
    if (membershipProvider != null && membershipProvider.ValidateUser(userName, password))
    {
         ClaimsIdentity identity = new GenericIdentity(userName, "Basic");
         return new RolePrincipal("CustomRoleProvider", identity);
    }

    return null;           
}

The key is in returning RolePrincipal, which points to your custom role provider.

Initially I returned new ClaimsPrincipal(identity), which gave me the problem described in the OP.