Blazor Server完美实现Cookie Authorization and Authentication

Blazor server-side application用Microsoft.AspNetCore.Identity.EntityFrameworkCore实现Authorization 和 Authentication 完整教程。

本方案只适用于Blazor Server-Size Application

完整项目源代码,参考: https://github.com/neozhu/CleanArchitectureWithBlazorServer

需要引用的类库如下:

    
    
    
    
    
      all
      runtime; build; native; contentfiles; analyzers; buildtransitive
    
    
    
    
      all
      runtime; build; native; contentfiles; analyzers; buildtransitive
    
    
    
    
    
    

  

这里的实现方式和Asp.net core 3.0,5.0,6.0, 7.0 几乎一样的配置,但又也有一些特殊之处。下面我分享一下的代码。

从上面引用的类库发现我并使用的是Microsoft.AspNetCore.Identity.EntityFrameworkCore + Duende.IdentityServer 都已经升级到最新版本。

配置 Microsoft.AspNetCore.Identity.EntityFrameworkCore 

用于生成需要后台表

Blazor Server完美实现Cookie  Authorization and Authentication插图

 

 

 这里和微软官方的文档略有不同我使用的AddIdentity方法。

添加 Authorization and Authentication 配置

Blazor Server完美实现Cookie  Authorization and Authentication插图1

 

 

 这类servicescollection配置和asp.net core cookie认证是一直,只是这里不需要配置Login,Logout路径

开发一个登录Blazor Component(Page)

Blazor Server完美实现Cookie  Authorization and Authentication插图2

Blazor Server完美实现Cookie  Authorization and Authentication插图3

 

 重点这里需要生成一个Token,而不是直接传用户名+密码,因为安全 不能明文传输密码。这里我们需要调用auth/login?token=.... 实现登录

AuthController 用户登录并获取授权

Blazor Server完美实现Cookie  Authorization and Authentication插图4

 

 这里的写法和asp.net core登录一样都使用SignInManager 登录成功后和asp.net core应用一样保存于账号相关的所有授权比如Roles和Claims 

如何需要自定义添加自定义的内容比如下面的TenantId TenantName ,ApplicationClaimsIdentityFactory就是用于添加需要内容。

Blazor Server完美实现Cookie  Authorization and Authentication插图5

 

 获取当前登录的账号信息

Blazor Server完美实现Cookie  Authorization and Authentication插图6

 

 之前Blazor Server-Side application 是不支持 IHttpContextAccessor获取账号信息,现在竟然可以了。

Blazor server Component调用UserManager需要注意的地方

Blazor Server完美实现Cookie  Authorization and Authentication插图7

 

Component需要继承 添加 @inherits OwningComponentBase

Blazor Server完美实现Cookie  Authorization and Authentication插图8

 

 需要通过ScopedServices.GetRequiredService>(); 创建才安全

希望对学习Blazor的同学有帮助。

 

文章来源于互联网:Blazor Server完美实现Cookie Authorization and Authentication

THE END
分享
二维码