Owin+ASP.NET Identity淺析系列(四)實現用戶角色


在今天,讀書有時是件“麻煩”事。它需要你付出時間,付出精力,還要付出一份心境。--僅以《Owin+ASP.NET Identity淺析系列》來祭奠那逝去的……

通過Owin+ASP.NET Identity淺析系列(三)框架結構分析一文,我們大概了解了IdentityModels、IdentityConfig和Startup三個文件是做什么的

使用VS2015新建MVC項目之后,我們翻閱這三個文件會發現,微軟並沒有幫我們生成角色的相關代碼,但是項目中只要牽涉到會員,就很少不牽涉角色的,蛋疼啊!!!好吧,還好Identity很強大,我們只需要寫一些類似ApplicationUser的代碼就可以實現會員角色功能了,開始折騰!!!

因為微軟和Identity的強大,我們只需要仿寫ApplicationUser的代碼即可!

第一步:做下數據庫准備吧,微軟很蛋疼,如果你使用它的角色管理器新建角色,角色表必須包含一個字段Discriminator,這個字段的意思是區分IdentityRole和你自己的Role,因此我們不得不在表里添加一個這樣的字段(誰讓微軟已經造好了輪子,咱就用吧)

create table aspnetroles
(
	Id char(32) primary key,
	Name varchar(50) not null comment '角色名稱',
	Discriminator varchar(50) null comment '區分IdentityRole和自定義Role',
	Description varchar(100) null comment '描述',
	CreateTime datetime not null comment '創建時間'
) comment '用戶角色表';

 備注:描述和創建時間字段,是我擴展的字段,仿照擴展用戶屬性

第二步:在IdentityModels類文件中新建ApplicationRole實體類(是不是跟ApplicationUser很類似)

// 可以通過向 ApplicationRole 類添加更多屬性來為角色添加配置文件數據
public class ApplicationRole : IdentityRole
{
    /// <summary>
    /// 角色描述
    /// </summary>
    public string Description { get; set; }

    /// <summary>
    /// 創建時間
    /// </summary>
    public DateTime CreateTime { get; set; }

    public ApplicationRole()
    {
        this.Id = System.Guid.NewGuid().ToString("N");
    }
}

 第三步:在IdentityConfig類文件中新建ApplicationRoleManager角色管理器

// 配置此應用程序中使用的應用程序角色管理器。RoleManager 在 ASP.NET Identity 中定義,並由此應用程序使用。
public class ApplicationRoleManager : RoleManager<ApplicationRole>
{
    public ApplicationRoleManager(IRoleStore<ApplicationRole, string> store) : base(store) { }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        return new ApplicationRoleManager(new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>()));
    }
}

 第四步:在Startup.Auth類文件中,配置角色管理器

// 配置數據庫上下文、用戶管理器、角色管理器和登錄管理器,以便為每個請求使用單個實例
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

 第五步:OK到此,我們就可以像獲取用戶管理器一樣,獲取角色管理器了

protected IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } }

protected ApplicationUserManager UserManager { get { return HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } }

protected ApplicationRoleManager RoleManager { get { return HttpContext.GetOwinContext().GetUserManager<ApplicationRoleManager>(); } }

 備注:拿到角色管理器后,你可以通過RoleManager.AddToRole(userId, roleName)方法將用戶加入角色,這樣這個用戶就可以訪問被標注[Authorize(Roles = "roleName")]的資源了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM