1

我在我的 mvc 项目中使用表单身份验证。
我创建了一个 CustomRoleProvider 并实现了两种方法:
IsUserInRoleGetRolesForUser

网页配置

<roleManager defaultProvider="CustomRoleProvider" enabled="true">
  <providers>
    <clear />
    <add name="CustomRoleProvider"  type="SASS.UI.CustomRoleProvider" connectionStringName="AfterSaleConnection"  />
  </providers>
</roleManager>

过滤器配置

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    ...
    filters.Add(new AuthorizeAttribute());
}

自定义角色提供者

public class CustomRoleProvider : RoleProvider
{
    private readonly IUserService _userServices;


    public CustomRoleProvider()
    {

        this._userServices = new UserServices(new Context());
    }
    public override bool IsUserInRole(string username, string roleName)
    {

        var user = _userServices.GetUser(username.GetUserId());

        if (user.IsAdmin)
            return true;

        return user.UserAccess.Any(y => (y.Role.ToString().ToLower() == roleName.ToLower()));
    }

    public override string[] GetRolesForUser(string username)
    {
        var user = _userServices.GetUser(username.GetUserId());

        List<string> accessList = new List<string>();

        if (user.UserAccess.Any(x => x.Role == Access.Admin))
        {
            foreach (Access access in Enum.GetValues(typeof(Access)))
            {

                accessList.Add(access.ToString().ToLower());
            }
            return accessList.ToArray();
        }
        var roles= user.UserAccess.Select(x => x.Role.ToString().ToLower()).ToArray();
        return roles;
    }

    public override void CreateRole(string roleName)
    {
        throw new NotImplementedException();
    }

    public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
    {
        throw new NotImplementedException();
    }

    public override bool RoleExists(string roleName)
    {
        throw new NotImplementedException();
    }

    public override void AddUsersToRoles(string[] usernames, string[] roleNames)
    {
        throw new NotImplementedException();
    }

    public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
    {
        throw new NotImplementedException();
    }

    public override string[] GetUsersInRole(string roleName)
    {
        throw new NotImplementedException();
    }

    public override string[] GetAllRoles()
    {
        throw new NotImplementedException();
    }

    public override string[] FindUsersInRole(string roleName, string usernameToMatch)
    {
        throw new NotImplementedException();
    }

    public override string ApplicationName { get; set; }
}

authorize我还在控制器上方 添加了属性和如下操作:

[Authorize(Roles = "admin")]
public virtual ActionResult List()
{
    return View("CustomerList");
}

但是当用户请求访问他没有admin角色的操作时,他可以打开它!

我运行我的项目并在方法中设置了一个断点IsUserInRoles,但它永远不会触发!问题出在哪里?

4

0 回答 0