FormsAuthentication 和数据库支持的嵌套角色

FormsAuthentication and database backed nested roles

我正在阅读用于迁移遗留应用程序的 FormsAuthentication。此应用程序为 roles/permissions 用户使用以下结构:

class Account
{
    public ISet<Role> Roles
    {
        get;
        set;
    }

    public static bool Has(Permission permission_)
    {
        foreach (Role role in Roles) {
            if (role.Permissions.Contains(permission_)) {
                return true;
            }
        }

        return false;
    }

}

class Role
{
    public ISet<Permission> Permissions
    {
        get;
        set;
    }
}

public enum Permission
{
    ACCESS_COMPONENT_XYZ
    EDIT_FIELD_ABC
    VIEW_ENTITY_123
}

Roles只是权限的集合,在代码本身中,只检查权限,例如

model.CanEditFieldAbc = account.Has(Permission.EDIT_FIELD_ABC);

所有这些都由使用 NHibernate 的数据库支持。现在,据我了解 FormsAuthentication,这对角色使用 "one-dimensional" 方法。意思是,我在 AuthenticationToken 中只有一个字段来填写我的权限。

我认为我需要以某种方式将帐户实体的所有权限获取到当前经过身份验证的令牌中。我的问题是:我该怎么做?我了解如何进行身份验证,但不知道如何将我的自定义权限集(例如字符串)获取到该令牌中?

目前我的登录控制器是这样的:

// "Accounts" is a NHibernate repository on the base controller
Account account = Accounts.Unique(form_.Name);

if (account != null) {
    byte[] salt = Convert.FromBase64String(account.Salt);
    byte[] password = Convert.FromBase64String(account.Password);

    if (PWDTK.ComparePasswordToHash(salt, form_.Password, password)) {
        FormsAuthentication.SetAuthCookie(form_.Name, false);
        // How to get the complete set of "account.Roles -> Permission" into the Cookie/Token?
    }
    else {
        throw new AuthenticateException("Wrong credentials");
    }
}
else  {
    throw new AuthenticateException("Wrong credentials");
}

当然,我可以只为每个请求从数据库中获取当前帐户,然后在其中包含 roles/permissions 的集合(感谢 nhibernate 延迟加载等),但是鉴于 FormsAuthenticate 已经提供了与此类似的内容,这似乎是错误的?

角色应该由角色提供者处理。在您的情况下,您应该 write and configure 您自己的角色提供者。

登录时,您的代码不必关心提供角色,框架将使用您在配置中定义的角色提供者。您只需要在成功登录时调用 RedirectFromLoginPage(如果您不想使用内置重定向,则调用 SetAuthCookie)。

然后要检查角色,您应该使用 User IsInRole 方法。