reaper_unique
reaper_unique

Reputation: 2931

Role provider and System.Web.Security.Roles

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);

    }

Upvotes: 1

Views: 4087

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039398

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>

Upvotes: 1

Related Questions