Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8217089
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T12:21:10+00:00 2026-06-07T12:21:10+00:00

I’m having an issue with a custom role provider in ASP.net MVC4. I implemented

  • 0

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 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T12:21:12+00:00Added an answer on June 7, 2026 at 12:21 pm

    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>();
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am trying to understand how to use SyndicationItem to display feed which is
I used javascript for loading a picture on my website depending on which small
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I would like to run a str_replace or preg_replace which looks for certain words
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I have a text area in my form which accepts all possible characters from
I'm having trouble keeping the paragraph square between the quote marks. In firefox the
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.