加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-identity – ASP.net身份 – UserManager如何访问角色?

发布时间:2020-12-16 06:49:49 所属栏目:asp.Net 来源:网络整理
导读:…而我们只在Microsoft.AspNet.Identity中. (我们甚至没有查看Microsoft.AspNet.Identity.EntityFramework的基本实现.) UserManager类仅接收IUserStore TUser在构造函数.它没有IUserRoleStore TUserRole我想这将需要访问以确定UserManager.IsInRoleAsync(字
…而我们只在Microsoft.AspNet.Identity中. (我们甚至没有查看Microsoft.AspNet.Identity.EntityFramework的基本实现.)

UserManager类仅接收IUserStore< TUser>在构造函数.它没有IUserRoleStore< TUserRole>我想这将需要访问以确定UserManager.IsInRoleAsync(字符串,字符串)是否.

我认为UserStore的实现也会有一个IsInRoleAsync(字符串,字符串)函数(然后它会都有意义),但事实并非如此.

另一件奇怪的事情 – 如果UserManager在其实现中知道所有内容,那么UserManager如何能够执行密码设置和重置是我们正在处理IUser – 只有字符串Id和字符串UserName作为属性?

解决方法

好的,经过大量的挖掘和幸运的发现 – 事实证明,Microsoft.AspNet.Identity.Core附带了一些其他接口,特别是IUserRoleStore< TUser>和IUserPasswordStore< TUser>其中“继承”(实施)IUserStore< TUser>.

因此,如果我们想要角色管理功能,我们实现IUserRoleStore< TUser>:

class MyUser : IUser
{
        // Additional properties and functions not shown for brevity.
}

class MyUserStore : IUserRoleStore<MyUser>
{
    public bool IsInRole(string username,string role)
    {
       // Implementation not show for brevity.
    }


    /* We would then implement the rest of the required functions.

       We would have a data context here that has access to users,user-roles,and roles.
    */
}

现在我们可以将MyUserStore传递给UserManager< TUser>,因为MyUserStore是IUserRoleStore< TUser>,这是一个IUserStore< TUser>:

UserManager<MyUser> UM = new UserManager<MyUser>(new MyUserStore());

那么,我怀疑UserManager的源代码< TUser>使用反射来确定在构造函数中传入它的商店是否实现了IUserStore< TUserStore>的“子接口”之一,以便能够执行角色检查(如果它实现IUserRoleStore< TUser>)或密码设置/重置(如果它实现了IUserPasswordStore< TUser>).

我希望你发现这很有用,因为大多数文档(MVC教程等)都没有告诉我们这个细节.他们告诉我们使用UserStore< TUser> Microsoft.AspNet.Identity.EntityFramework的实现 – 我们所要做的就是传入一个自定义User对象(实现IUser),我们很高兴.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读