角色提供程序和System.Web.Security.Roles

时间:2013-02-23 18:05:50

标签: c# asp.net-mvc-4 authorization

我对如何在我的asp.net MVC4剃刀项目中使用角色感到困惑。 两者之间有什么区别,主要是,如何使用authorize属性并使其成为当我检查经过身份验证的用户的角色时,它会转到我的自定义角色提供程序。或者我在这里混合了什么?

更具体:

我有一个管理员控制器,其中具有“管理员”角色的用户可以执行CRUD操作。 在我的控制器中,我应用以下属性:

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

假设authorize属性将在后端使用我的客户角色提供程序是否正确?如果是这样,为什么它对我不起作用?

我的自定义角色提供程序类的一部分:

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

我做错了什么?用户如何正确地进行身份验证,如何:

    [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="" });
    }

从我的自定义角色提供程序检查他或她的授权?

修改

我的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>

       

编辑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 个答案:

答案 0 :(得分:0)

  

假设authorize属性将使用my是否正确   客户角色提供者在后端?

  

如果是这样,为什么它对我不起作用?

您可能忘记在web.config中注册此自定义角色提供程序,并使其成为此应用程序的默认提供程序:

<roleManager defaultProvider="CustomRoleProvider" enabled="true">
    <providers>
        <clear />
        <add 
            name="CustomRoleProvider"
            type="Somenamespace.CustomRoleProvider"
        />
    </providers>
</roleManager>