【问题标题】:Role provider and System.Web.Security.Roles角色提供者和 System.Web.Security.Roles
【发布时间】:2013-02-23 18:05:50
【问题描述】:

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

更具体的:

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

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

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

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

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>

编辑二

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

    }

【问题讨论】:

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


    【解决方案1】:

    假设授权属性将使用我的 后端的客户角色提供者?

    是的。

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

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

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

    【讨论】:

    • 啊,不,忘了说,web.config 应该是正确的。我有你提供的相同结构。见编辑。
    • 那么这应该工作。还要确保您已覆盖 GetRolesForUser 方法。
    • 因此,如果我在 IsUserInRole 方法的自定义角色提供程序中放置一个断点,并且我将授权属性放置在概览类的顶部,它应该停在那里吗?每次都需要将代码放在控制器顶部的edit II中吗?
    • 不,当然不是。 Authorize 属性使用GetRolesForUser 方法而不是IsUserInRole 方法。所以这就是你应该放置断点的地方。
    • 哦。 [Authorize(Roles = "administrator")] 不检查经过身份验证的用户是否具有正确的角色? IE。返回真还是假?
    猜你喜欢
    • 2011-02-17
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 2012-04-08
    • 2013-10-21
    • 2017-07-26
    • 1970-01-01
    相关资源
    最近更新 更多