2

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;
    }
}
Community
  • 1
  • 1
stimms
  • 42,945
  • 30
  • 96
  • 149
  • Could you post the roleprovider source code? – Xharze Apr 16 '12 at 20:18
  • Added the source but now I'm thinking that I've somehow hooked up the role provider incorrectly. I'm looking at http://blogs.msdn.com/b/alikl/archive/2010/11/18/authorization-with-rolemanager-for-claims-aware-wif-asp-net-web-applications.aspx – stimms Apr 16 '12 at 20:57
  • Good question -- I'm having the same problem. Custom role provider gets hit when I call System.Web.Security.Roles.GetRolesForUser(username) in my custom attribute...and it loads the correct roles from the database but [RequestKeyAuthorizeAttribute(Roles="Admin")] works on a controller method even when the only role returned is "Administrator". – Timothy Lee Russell Jul 11 '12 at 04:43
  • Could you please make sure this is the code used in your real application? I see you always return true in IsUserInRole. Does this method return false on your side? Please try to debug into the role provider and verify if it indeed gets executed. Best Regards, Ming Xu. – Ming Xu - MSFT Apr 17 '12 at 09:03
  • This is obviously just testing code and I would perform some logic in the real application. When I break on the UserInRole I find that it is not hit by the AuthorizeAttribute and, in fact, when I manually run User.IsInRole from a controller it is not hit. What I'm seeing is that the IPrincipal doesn't seem to have the correct RoleProvider set. – stimms Apr 17 '12 at 13:12
  • Debugging a similar problem, I've found that my custom role provider works fine on the `System.Web.Mvc.Controller` that I use to render the initial page, but always returns `false` on any Web Api controllers `System.Web.Http.ApiController` – chrisjsherm Feb 18 '13 at 20:42

4 Answers4

2

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>();
}
Timothy Lee Russell
  • 3,719
  • 1
  • 35
  • 43
  • I found this thread because I have run into the same problem after upgrading my MVC version. I don't yet have an answer and there is a big downside to the accepted answer here. If you replace user.IsinRole with custom logic based on a custom GetRolesForUser call, you eliminate the built in caching. That means every controller call with an authorize attribute will have to make a call to the database. I don't have enough characters here to post the full reflection results with the code for user.Isinrole but that's the gist of it. – EGP Apr 26 '17 at 14:21
  • Sure, that make sense. I didn't know about the built-in caching but since you would be implementing the GetRolesForUser method anyway, it would be simple enough to just cache the results in Redis or some other in-memory name/value store. – Timothy Lee Russell Apr 28 '17 at 01:21
  • Very true, you could do your own caching. More code to maintain but not a bad solution at all. In my case I ended up going back and upgrading again and then user.IsInRole worked. I must have done something wrong in my initial upgrade. My root problem was that the httpcontext.user was not a roleprincipal but after I did the upgrade again it is. – EGP May 06 '17 at 13:00
0

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.

Ming Xu - MSFT
  • 2,116
  • 1
  • 11
  • 13
0

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);
    }
}
Jacob Brewer
  • 2,574
  • 1
  • 22
  • 25
0

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.

Stanislav
  • 1,074
  • 1
  • 9
  • 11