1

I'm confused on how to use roles in my asp.net MVC4 razor project. What is the difference between the two and mainly, how can I use the authorize attribute and make it so that when I check for the role of an authenticated user it goes to my custom role provider. Or am I mixing things up here?

More concrete:

I have an admin controller where a user with the role "administrator" can do CRUD stuff. In my controller I apply the following attribute:

[Authorize(Roles = "administrator")]
public class OverviewController : Controller

Is it correct to assume that the authorize attribute will use my custome Role provider in the back end? If so, why doesn't it work for me?

Parts of my custom role provider class:

public sealed class CustomRoleProvider : RoleProvider
{
    public override void Initialize(string name, NameValueCollection config)
    {
        if (config == null) throw new ArgumentNullException("config");

        if (name.Length == 0) name = "CustomRoleProvider";

        if (String.IsNullOrEmpty(config["description"]))
        {
            config.Remove("description");
            config.Add("description", "Custom Role Provider");
        }

        //Initialize the abstract base class.
        base.Initialize(name, config);

        _applicationName = Helpers.GetConfigValue(config["applicationName"], System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
    }

    public override bool IsUserInRole(string email, string roleName)
    {
        bool isValid = false;

        var usersInRole = _unitOfWork.UsersRepository.Get(uir => uir.email == email && uir.Roles.Name == roleName);

        if (usersInRole != null) isValid = true; 

        return isValid;
    }

What am I doing incorrect? How can a user, when he or she is correctly authenticated like so:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult LoginValidate(Authentication authentication, string returnUrl)
    {
        string email    = authentication.email;
        string password = authentication.password;
        bool rememberMe = authentication.rememberMe;
        if(string.IsNullOrEmpty(returnUrl)) returnUrl = "/";

        //If the filled in fields are validated against the attributes
        if (ModelState.IsValid)
        {
            if (MembershipService.ValidateUser(email, password))
            {
                FormsService.SignIn(email, rememberMe);

                return RedirectToAction("Index", "Home", new { area="" });
            }

            ModelState.AddModelError("", Resources.Resources.Error_incorrect_emailPassword);

        }   

        // Add the ModelState dictionary to TempData here.
        TempData["ModelState"] = ModelState;

        return RedirectToAction("index", "Home", new { area="" });
    }

Be checked on his or hers authorization from my custom role provider?

Edit

My web.config:

<roleManager enabled="true" defaultProvider="CustomRoleProvider" cacheRolesInCookie="true" >
  <providers>
    <clear />
    <add name="CustomRoleProvider" type="ArtWebShop.Common.CustomRoleProvider" connectionStringName="ArtWebshopEntities" applicationName="/" />
  </providers>
</roleManager>

  <membership defaultProvider="CustomMembershipProvider">
  <providers>
    <clear />
    <add name="CustomMembershipProvider" type="ArtWebShop.Common.CustomMembershipProvider" connectionStringName="ArtWebshopEntities" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="0" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
  </providers>
</membership>

Edit II

    public override bool ValidateUser(string email, string password)
    {
        string salt = _unitOfWork.UsersRepository.GetSalt(email);
        string hashedPassword = Helpers.CreatePasswordHash((password), salt);

        return _unitOfWork.UsersRepository.UserIsValid(email, hashedPassword);

    }

1 Answer 1

1

Is it correct to assume that the authorize attribute will use my custome Role provider in the back end?

Yes.

If so, why doesn't it work for me?

You probably forgot to register this custom role provider in your web.config and make it the default provider for this application:

<roleManager defaultProvider="CustomRoleProvider" enabled="true">
    <providers>
        <clear />
        <add 
            name="CustomRoleProvider"
            type="Somenamespace.CustomRoleProvider"
        />
    </providers>
</roleManager>
11
  • Ah, nop, forgot to mention that, web.config should be correct. I've the same structure you are providing. See edit. Feb 23, 2013 at 18:17
  • Then this should work. Also make sure you have overridden the GetRolesForUser method. Feb 23, 2013 at 18:17
  • So if I place a breakpoint in my custom Role Provider at the method IsUserInRole and I place the authorize attribute at the top of my overview class it should stop there? Is it needed to place the code in edit II at the top of my controller everytime? Feb 23, 2013 at 18:21
  • 1
    No, of course not. The Authorize attribute uses the GetRolesForUser method and not the IsUserInRole method. So that's where you should be placing your breakpoint. Feb 23, 2013 at 18:22
  • Oh. Doesn't [Authorize(Roles = "administrator")] check whether or not the authenticated user has the correct role? I.e. return true or false? Feb 23, 2013 at 18:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.