Day 21 ASP.NET Core Identity

今天来实作身分验证的部分,笔者此前是用 ASP.NET Core Web API 搭配 Blazor,使用者第一次成功登入时,在後端将 Role、Claim 等权限储存在 JWT,将 JWT 存在浏览器的 LocalStorage 里面,前端再自己覆写 AuthenticationStateProvider,去检查 LocalStorage 的 JWT,接着将 AuthenticationState 当作 CascadingParameter 层层传递到各 Component,这样就不需要不停跟後端交换资料,这是个很宝贵的经验,让笔者对身分验证有深入了解,这次笔者试试看 ASP.NET Core 自己的 Identity。

首先去 NeGet 下载 3 个套件,分别为Microsoft.AspNetCore.Identity.EntityFrameworkCoreMicrosoft.AspNetCore.Identity.UIMicrosoft.VisualStudio.Web.CodeGeneration.Design,第 1 个是 Identity 必备套件,如果想自己实作 JWT 的话,只需要下载第一个套件,再下载 JWT 相关套件(Microsoft.AspNetCore.Authentication.JwtBearer)即可,後面 2 个都是让 ASP.NET Core Identity帮我们产生预设 Identity 页面的套件。

接着去BlazorServer.ModelsAppDbContext,将继承的DbContext改为IdentityDbContext,代表接下来用的 DB 跟 Identity有关系。
https://ithelp.ithome.com.tw/upload/images/20210921/20140893chTmhPPKga.png

在 BlazorServer 专案按右键,选择「加入」,选择「新增 Scaffold 项目」,切换到「识别」页签,选择识别。
https://ithelp.ithome.com.tw/upload/images/20210921/20140893Znk64dPSAl.pnghttps://ithelp.ithome.com.tw/upload/images/20210921/20140893bMbu81WdOW.png

勾选「覆写所有档案」,资料内容类别选择AppDbContext,要注意的是,如果刚才没将继承的类别改成IdentityDbContext,就不会有AppDbContext可以选,必须点右边的「+」符号自己新增一个IdentityDbContext
https://ithelp.ithome.com.tw/upload/images/20210921/20140893VL6dwICj4g.png

这时候有可能遇到这种「OnInitializedAsync(): 未找到任何合适的方法可覆写」的错误讯息,这通常是 Visual Studio 的问题,先将这里注解,重复一次上一段的作法就可以。
https://ithelp.ithome.com.tw/upload/images/20210921/20140893SZ4V1pt7Ou.png
https://ithelp.ithome.com.tw/upload/images/20210921/20140893am52YankUo.png

接着去Startup.csConfigureServices()Configure()加上身分验证的服务,Identity 预设将验证资讯存在 Cookie。
ConfigureServices()

            services.AddAuthentication("Identity.Application").AddCookie();
            services.AddIdentity<IdentityUser, IdentityRole>()
                .AddDefaultTokenProviders()
                .AddDefaultUI()
                .AddEntityFrameworkStores<AppDbContext>();

Configure()

            app.UseAuthentication();
            app.UseAuthorization();

https://ithelp.ithome.com.tw/upload/images/20210922/201408932rMh4kU8Cf.png
https://ithelp.ithome.com.tw/upload/images/20210922/20140893e4WlnzasmH.png

接着在套件管理器主控台执行两段指令,Add-Migration IdentitySupport新增Migration,Update-Database更新 DB,去看资料库,可以看到多了 6 张表,其中最常用到的就是 AspNetUsers、AspNetRoles 及 AspNetUserRoles,如果以 Claim 处理权限的话,就会用到 AspNetUserClaims。
https://ithelp.ithome.com.tw/upload/images/20210921/20140893kbxnwpL9NJ.png

专案则多了一个 Areas 资料夹,里面就是 ASP.NET Core Identity 的实作,包括了登入系统、帐号系统、管理系统。
https://ithelp.ithome.com.tw/upload/images/20210922/20140893EEvzmnTlVe.png

我们去NavMenu.razor加上通往 Login 的 NavLink,在相对路径中 Areas 跟 Pages 可以省略。

        <li class="nav-item px-3">
            <NavLink class="nav-link" href="Identity/Account/Login" Match="NavLinkMatch.All">
                <span class="bi bi-file-earmark-lock2 h4 p-2 mb-0" aria-hidden="true"></span> Login
            </NavLink>
        </li>

启动网站後,从左边 Nav 前往 Login页面,可以看到已经有个完善的登入系统,包括注册、登入、忘记密码等等功能,就连注册密码的规则也有,我们照规则注册一个帐号,资料库也产生了刚刚注册的帐号。
https://ithelp.ithome.com.tw/upload/images/20210922/20140893autqQOD9W7.png
https://ithelp.ithome.com.tw/upload/images/20210922/20140893se1vVy0109.png
https://ithelp.ithome.com.tw/upload/images/20210922/20140893e8hS1KQou8.png

Ref:Claims-based authorization in ASP.NET Core

Ref:Claim type and claim value in claims policy based authorization in asp net core

Ref:ASP NET Core Identity tutorial from scratch

Ref:Unable to resolve service for type IEmailSender while attempting to activate RegisterModel


<<:  分散式资料库:分散式理论

>>:  Day6中秋节最後还是要吃肉肉阿-欧式地中海风马铃薯柠檬炖鸡

[Day 7] 从零开始的股票预测 - 异常值侦测

一、异常值(Outliers) 异常值是指某些大幅度偏离正常值的资料点,来源可能是测量异常或记录异常...

【程序】我为什麽转职,转职後快乐吗 转生成恶役菜鸟工程师避免 Bad End 的 30 件事 - 22

我为什麽转职, 转职後快乐吗 了解自己 相信自己 自我实现 ...

D9. 学习基础C、C++语言

D9: while跟 do-while的差别 我原本一直以为do-while是要判断式成立时才会执行...

Day 30 云端守门员

来到了最後一天,我们也剩下最後一片云要一起来探索。今天就来谈谈云端的资安,以此来总结我们这一趟经历两...

[Day22] React x TS 中的 Event Handler

今天来分享一个小东西,记得以前一开始用 React 搭配 TypeScript 开发专案的时候,在...