[Blazor] 一文理清 Blazor Identity 鉴权验证

打印 上一主题 下一主题

主题 781|帖子 781|积分 2343

一文理清 Blazor Identity 鉴权验证

择要

在现代Web应用程序中,身份认证与授权是确保应用安全性和用户数据掩护的关键环节。Blazor作为基于C#和.NET的前端框架,提供了丰富的身份认证与授权机制。本文将深入解析Blazor的身份认证框架的构成,比较不同渲染模式下鉴权逻辑的异同,并通过具体案例演示如安在Blazor Server和Blazor WebAssembly中实现身份认证。通过本文的学习,读者将能够更好地理解并应用Blazor中的Identity,以构建安全可靠的Web应用程序。
鉴权框架的构成

Blazor的身份认证框架主要由以下三个核心部分组成:
基架: AuthenticationMiddleware (Microsoft.AspNetCore.Authentication)

AuthenticationMiddleware是ASP.NET Core中用于处理身份认证的中心件组件。它位于请求处理管道中,负责验证用户的身份并构建ClaimsPrincipal对象,将其附加到HttpContext.User属性中。全部后续的中心件和请求处理程序都可以访问该用户对象,从而了解当前请求的身份信息。
在Blazor应用程序中,AuthenticationMiddleware的作用是拦截HTTP请求,检查请求中是否包含有效的认证凭据(例如Cookie、JWT等)。如果凭据有效,它将解析并构建用户的身份信息;如果无效,则将用户视为未认证状态。


Cookie认证
JWT认证
其他方案
成功
失败


通过
不通过
HTTP请求
是否需要认证
直接访问资源
Authentication中心件
检查认证方案
解析Cookie
解析Authorization Header
...
验证Cookie有效性
验证Token署名
验证相应凭证
验证结果
创建ClaimsPrincipal
返回401/403
设置HttpContext.User
是否需要授权
Authorization中心件
访问资源
检查授权策略
访问资源
返回403

引用:
后端鉴权逻辑服务: IdentityCore (Microsoft.AspNetCore.Identity)

IdentityCore是ASP.NET Core提供的完整的身份管理框架。它为开发者提供了处理用户注册、登录、角色管理、暗码重置等功能的 APIs 和服务。IdentityCore高度可定制,可以使用不同的数据存储方式(如Entity Framework CoreMongoDB等)和暗码哈希算法。
Blazor Server模式下,IdentityCore通常与AuthenticationMiddleware结合使用。后端服务器负责处理全部与身份相关的逻辑,包括验证用户凭据、管理用户数据和生成身份认证令牌等。
核心架构图

IdentityUser
+string Id
+string UserName
+string Email
+string PasswordHash
+string SecurityStamp
+bool EmailConfirmed
+bool TwoFactorEnabled
IdentityRole
+string Id
+string Name
+string NormalizedName
UserManager
+CreateAsync()
+FindByIdAsync()
+AddToRoleAsync()
+CheckPasswordAsync()
+GenerateEmailConfirmationTokenAsync()
SignInManager
+PasswordSignInAsync()
+SignInAsync()
+SignOutAsync()
+TwoFactorAuthenticatorSignInAsync()
RoleManager
+CreateAsync()
+FindByIdAsync()
+AddClaimAsync()
IdentityDbContext
+DbSet Users
+DbSet Roles
+DbSet UserClaims
+DbSet RoleClaims
UserStore
+CreateAsync()
+UpdateAsync()
+FindByIdAsync()
+AddToRoleAsync()
RoleStore
+CreateAsync()
+UpdateAsync()
+FindByIdAsync()
IdentityOptions
+PasswordOptions
+LockoutOptions
+UserOptions
+SignInOptions
IdentityBuilder
+AddEntityFrameworkStores()
+AddDefaultTokenProviders()
+AddDefaultUI()

配置与启动流程 (图中的配置函数非常原始,案例中会使用较新的简化函数,不过最终都是调用它们)

OptionsEFIdentityServicesStartupOptionsEFIdentityServicesStartup服务配置阶段配置暗码规则锁定策略用户选项等中心件配置ConfigureServices()AddIdentity()注册核心服务AddEntityFrameworkStores()Configure()UseAuthentication()UseAuthorization()配置认证中心件配置授权中心件
用户注册与认证流程

EmailDBStoreSignInManagerUserManagerControllerClientEmailDBStoreSignInManagerUserManagerControllerClient注册流程alt[需要邮箱验证]登录流程alt[启用2FA]注册请求CreateAsync(user, password)验证暗码规则生成SecurityStampHash暗码CreateAsync(user)保存用户GenerateEmailConfirmationTokenAsync发送确认邮件登录请求PasswordSignInAsyncFindByNameAsyncFindByNameAsync查询用户CheckPasswordAsync要求2FA验证提供2FA码TwoFactorSignInAsync创建身份票据设置认证Cookie
授权与角色管理流程(更侧重于使用AuthorizationMiddleware)

DBStoreRoleManagerUserManagerControllerClientDBStoreRoleManagerUserManagerControllerClient角色管理授权验证alt[基于角色][基于Claims]创建角色请求CreateAsync(role)CreateAsync(role)保存角色分配角色请求AddToRoleAsync(user, role)AddToRoleAsync更新用户角色关系请求受掩护资源[Authorize(Roles = "Admin")]IsInRoleAsyncIsInRoleAsync查询角色关系GetClaimsAsyncGetClaimsAsync查询Claims
扩展点和自定义实现

«interface»
IUserStore
+CreateAsync()
+UpdateAsync()
+DeleteAsync()
+FindByIdAsync()
«interface»
IUserPasswordStore
+SetPasswordHashAsync()
+GetPasswordHashAsync()
«interface»
IUserRoleStore
+AddToRoleAsync()
+RemoveFromRoleAsync()
+GetRolesAsync()
«interface»
IUserClaimStore
+AddClaimsAsync()
+RemoveClaimsAsync()
+GetClaimsAsync()
CustomUserStore
-IRepository repository
+CreateAsync()
+UpdateAsync()
+FindByIdAsync()
«interface»
IPasswordHasher
+HashPassword()
+VerifyHashedPassword()
«interface»
IPasswordValidator
+ValidateAsync()
«interface»
IUserValidator
+ValidateAsync()

主要特点:
模块化设计:核心身份模子、用户管理服务、存储抽象层、验证器接口
灵活的扩展性:自定义用户模子、自定义存储实现、可配置的选项、验证器扩展
完整的认证流程:用户注册、暗码验证、双因素认证、外部登录
丰富的授权机制:基于角色、基于Claims、基于策略、动态授权
安全特性:暗码哈希、账户锁定、安全戳验证、令牌管理
引用:
前端鉴权逻辑服务: AuthenticationStateProvider (Microsoft.AspNetCore.Components.Authorization)

AuthenticationStateProvider是Blazor中用于提供当前用户身份状态的抽象类。它的主要作用是向Blazor组件提供身份认证状态(AuthenticationState),以便组件能够根据用户的身份进行相应的显示和操作。
Blazor应用程序中,AuthenticationStateProvider的具体实现方式取决于应用的渲染模式和身份认证方案。对于Blazor Server,这个提供程序可以直接从服务器的HttpContext.User获取身份信息;对于Blazor WebAssembly,由于代码在客户端运行,需要通过其他方式(如调用后端API或解析令牌)获取用户身份。
状态存储Identity服务自定义AuthProviderAuthenticationStateProviderCascadingAuthenticationStateBlazor组件状态存储Identity服务自定义AuthProviderAuthenticationStateProviderCascadingAuthenticationStateBlazor组件初始化阶段alt[自定义认证逻辑][默认实现]状态访问alt[通过注入访问][通过级联参数访问]状态变动Server模式授权验证alt[未授权][已授权]组件初始化GetAuthenticationStateAsync()委托处理获取用户信息返回用户数据构建AuthenticationState缓存状态获取当前用户返回ClaimsPrincipalnew AuthenticationState()返回AuthenticationState通过级联参数提供状态[CascadingParameter]Task@inject AuthenticationStateProvider返回Provider实例GetAuthenticationStateAsync()await AuthenticationState获取User信息处理授权逻辑用户状态变动更新AuthenticationState更新缓存状态NotifyAuthenticationStateChanged关照状态变动触发重新渲染@attribute [Authorize]GetAuthenticationStateAsync()获取缓存状态返回状态重定向到登录页允许访问渲染受掩护内容
主要特点:
状态管理:缓存认证状态、状态变动关照、状态同步更新
组件集成:CascadingAuthenticationState提供状态共享、AuthorizeView用于条件渲染、Authorize特性支持
自定义能力:自定义认证逻辑、自定义授权策略、状态持久化
安全特性:状态验证、角色授权、Claims基础授权
性能优化:状态缓存、按需刷新、组件重渲染控制
引用:
不同渲染模式中鉴权逻辑的异同

相同点

组件在获取用户信息与鉴权状态时,都同一使用CascadingAuthenticationState

无论是Blazor Server还是Blazor WebAssembly,组件在需要访问用户身份信息时,都通过CascadingAuthenticationState提供的AuthenticationState。这使得组件能够以一致的方式获取用户的身份认证状态,无需关注底层的实现细节。
使用级联参数获取用户信息
  1. @code {
  2.     [CascadingParameter] private Task<AuthenticationState> stateTask { get; set; }
  3.     private ClaimsPrincipal user;
  4.     protected override async Task OnInitializedAsync()
  5.     {
  6.         var authState = await stateTask;
  7.         user = authState.User;
  8.     }
  9. }
复制代码
使用服务获取用户信息
  1. @inject AuthenticationStateProvider AuthenticationStateProvider
  2. @code {
  3.     private ClaimsPrincipal user;
  4.     protected override async Task OnInitializedAsync()
  5.     {
  6.         var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
  7.         user = authState.User;
  8.     }
  9. }
复制代码
引用:
不同点

Server模式 实现RevalidatingServerAuthenticationStateProvider(基于AuthenticationStateProvider) 重点在验证ClaimPrincipal中的安全戳

Blazor Server模式下,应用程序在服务器上运行,客户端通过SignalR持久连接与服务器通讯。默认情况下,Blazor Server使用ServerAuthenticationStateProvider,它直接从HttpContext.User获取用户的身份信息。
为了增强安全性,Blazor Server提供了RevalidatingServerAuthenticationStateProvider。它继承自ServerAuthenticationStateProvider,能够在指定的时间间隔内重新验证用户的身份状态。这主要通过检查ClaimsPrincipal中的安全戳(Security Stamp)来实现。当用户的安全戳发生变化(如暗码更改、账户被禁用等),该提供程序会检测到并更新用户的身份状态,要求用户重新登录。
HttpContext认证状态存储Blazor组件RevalidatingAuthProviderAuthenticationStateProviderBlazor CircuitSignalR HubCookie中心件数据库User StoreUserManagerSignInManagerIdentity服务认证中心件服务器浏览器用户HttpContext认证状态存储Blazor组件RevalidatingAuthProviderAuthenticationStateProviderBlazor CircuitSignalR HubCookie中心件数据库User StoreUserManagerSignInManagerIdentity服务认证中心件服务器浏览器用户SecurityStamp生成阶段Guid.NewGuid().ToString()如暗码修改/角色变动等alt[用户注册][安全相关操作]登录阶段包含用户Claims和SecurityStampHttpContext可用new AuthenticationState(Principal)认证状态持久化验证当前用户状态opt[需要重新验证]alt[首次请求或状态逾期]后台定期验证par[获取Claims中的SecurityStamp][获取数据库中的SecurityStamp]alt[SecurityStamp不匹配][SecurityStamp匹配]loop[每30分钟]注册请求CreateAsync生成新SecurityStamp保存用户信息存储SecurityStampUpdateSecurityStampAsync生成新SecurityStamp更新用户信息更新SecurityStamp登录请求SignInAsync验证凭据获取用户信息返回用户数据验证成功验证成功创建ClaimsPrincipal创建认证Cookie设置Cookie首次HTTP请求(带Cookie)返回初始HTML(App.razor)WebSocket连接请求(带Cookie)创建Circuit验证请求Cookie解析认证Cookie还原ClaimsPrincipal返回Principal创建AuthenticationState初始化认证状态存储认证状态GetAuthenticationStateAsync()检查状态是否需要重新验证返回验证时间ValidateAuthenticationStateAsync返回AuthenticationState用户交互处理请求❌无法访问HttpContext获取认证状态返回认证状态ValidateAuthenticationStateAsync从Claims获取SecurityStampGetSecurityStampAsync查询用户获取SecurityStamp返回当前SecurityStamp返回结果返回SecurityStamp更新认证状态NotifyAuthenticationStateChanged更新UI状态继续使用当前认证状态
引用:
Webassembly模式 实现AuthenticationStateProvider与HttpMessageHandler(可选) 重点在访问个人信息终结点(或从自包含令牌)解析ClaimPrincipal

Blazor WebAssembly模式下,应用程序在客户端浏览器中运行,没有直接访问服务器HttpContext的能力。因此,获取用户身份信息需要通过其他方式。例如,实现自定义的AuthenticationStateProvider,通过调用后端API(如用户信息终结点)获取用户信息,或者解析存储在客户端的JWT令牌来构建ClaimsPrincipal。
别的,为了在客户端向受掩护的API发送请求时主动附加身份认证令牌,或是在令牌逾期后主动刷新令牌,可以配置HttpClient使用自定义的HttpMessageHandler。这样,可以在请求头中添加必要的身份认证信息(如Bearer Token)或拦截401相应并刷新令牌重试请求。
Token服务后端APIHttpClientHandlerAuthenticationProviderBlazor组件Blazor WebAssembly应用浏览器用户Token服务后端APIHttpClientHandlerAuthenticationProviderBlazor组件Blazor WebAssembly应用浏览器用户alt[Token存在且未过-期][Token不存在或已-逾期]alt[验证成功][验证失败]alt[刷新成功][刷新失败]alt[Token有效][Token无效或逾期(返回401)]alt[刷新成功][刷新失败]alt[Token即将逾期][Token仍旧有效]loop[每固定时间间隔]打开应用URL加载Blazor WebAssembly应用初始化认证状态检查当地存储的Token使用现有Token设置为未认证状态返回认证状态渲染组件点击登录按钮调用Login方法发送登录请求(带用户凭据)验证用户凭据返回访问Token和刷新Token存储Token(如localStorage)更新认证状态为已认证关照认证状态已改变重新渲染受限页面返回错误信息关照登录失败GetAuthenticationStateAsync()使用Token请求用户信息(/userinfo)添加Authorization头返回用户信息返回AuthenticationState(包含用户信息)发起HTTP请求(携带API地址)拦截请求,添加Authorization头发送请求(带Token)返回请求数据返回数据返回401 Unauthorized关照Token无效实验刷新Token发送刷新Token请求验证刷新Token返回新的访问Token和刷新Token返回新的Token更新存储的Token关照重试原请求重新发送原请求(带新Token)返回请求数据返回数据返回刷新失败信息关照刷新失败清除Token,更新为未认证状态关照认证状态已改变(未认证)重定向到登录页或显示登录按钮检查Token有效期刷新Token验证刷新Token返回新的Token更新Token更新存储的Token返回刷新失败信息关照刷新失败清除Token,更新为未认证状态关照认证状态已改变(未认证)重定向到登录页或显示登录按钮无需操作
引用:
眼见为实:通过案例实现两种渲染模式的鉴权

下面,我们将通过具体的案例,演示如安在Blazor Server和Blazor WebAssembly应用程序中实现身份认证。
Server + Cookie

注册服务
  1. builder.Services.AddCascadingAuthenticationState();                                                         // 添加级联参数获取认证信息
  2. builder.Services.AddScoped<AuthenticationStateProvider, IdentityRevalidatingAuthenticationStateProvider>(); // 注册自实现的StateProvider
  3. builder.Services.AddAuthentication(options =>
  4. {
  5.     //在这里设定默认方案
  6.     options.DefaultScheme = IdentityConstants.ApplicationScheme;
  7.     options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
  8.     options.DefaultSignOutScheme = IdentityConstants.ExternalScheme;
  9. }).AddIdentityCookies(options =>
  10. {
  11. });
  12. builder.Services.AddIdentityCore<ApplicationUser>(options =>    //ApplicationUser继承自IdentityUser
  13. {
  14.     //在这里设定鉴权配置,比如验证邮箱(这里不验证)、密码规则(这里设置最简规则)
  15.     options.SignIn.RequireConfirmedAccount = false;
  16.     options.Password.RequiredLength = 6;
  17.     options.Password.RequireDigit = false;
  18.     options.Password.RequireLowercase = false;
  19.     options.Password.RequireNonAlphanumeric = false;
  20.     options.Password.RequireUppercase = false;
  21. })
  22.     .AddRoles<IdentityRole>()                                   //需要自定义角色时,继承IdentityRole
  23.     .AddEntityFrameworkStores<ApplicationDbContext>()           //ApplicationDbContext需要继承IdentityDbContext,其他ORM请自行搜索Store实现
  24.     .AddSignInManager()                                         //使用Cookie时,推荐注册
  25.     .AddDefaultTokenProviders();
  26. builder.Services.AddSingleton<IEmailSender<ApplicationUser>, IdentityNoOpEmailSender>();
  27. var app = builder.Build();
  28. app.UseAuthentication();
  29. app.UseAuthorization();
复制代码
其中,AddIdentityCookies方法的源代码如下:
  1.     /// <summary>
  2.     /// Adds the cookie authentication needed for sign in manager.
  3.     /// </summary>
  4.     /// <param name="builder">The current <see cref="AuthenticationBuilder"/> instance.</param>
  5.     /// <param name="configureCookies">Action used to configure the cookies.</param>
  6.     /// <returns>The <see cref="IdentityCookiesBuilder"/> which can be used to configure the identity cookies.</returns>
  7.     public static IdentityCookiesBuilder AddIdentityCookies(this AuthenticationBuilder builder, Action<IdentityCookiesBuilder> configureCookies)
  8.     {
  9.         var cookieBuilder = new IdentityCookiesBuilder();
  10.         cookieBuilder.ApplicationCookie = builder.AddApplicationCookie();
  11.         cookieBuilder.ExternalCookie = builder.AddExternalCookie();
  12.         cookieBuilder.TwoFactorRememberMeCookie = builder.AddTwoFactorRememberMeCookie();
  13.         cookieBuilder.TwoFactorUserIdCookie = builder.AddTwoFactorUserIdCookie();
  14.         configureCookies?.Invoke(cookieBuilder);
  15.         return cookieBuilder;
  16.     }
复制代码
IdentityNoOpEmailSender
  1.     public sealed class IdentityNoOpEmailSender : IEmailSender<ApplicationUser>
  2.     {
  3.         private readonly IEmailSender emailSender = new NoOpEmailSender(); //案例不实现真正的邮件发送
  4.         public Task SendConfirmationLinkAsync(ApplicationUser user, string email, string confirmationLink) =>
  5.             emailSender.SendEmailAsync(email, "Confirm your email", $"Please confirm your account by <a target="_blank" href='https://www.cnblogs.com/{confirmationLink}'>clicking here</a>.");
  6.         public Task SendPasswordResetLinkAsync(ApplicationUser user, string email, string resetLink) =>
  7.             emailSender.SendEmailAsync(email, "Reset your password", $"Please reset your password by <a target="_blank" href='https://www.cnblogs.com/{resetLink}'>clicking here</a>.");
  8.         public Task SendPasswordResetCodeAsync(ApplicationUser user, string email, string resetCode) =>
  9.             emailSender.SendEmailAsync(email, "Reset your password", $"Please reset your password using the following code: {resetCode}");
  10.     }
复制代码
IdentityRevalidatingAuthenticationStateProvider
  1. public sealed class IdentityRevalidatingAuthenticationStateProvider(
  2.         ILoggerFactory loggerFactory,
  3.         IServiceScopeFactory scopeFactory,
  4.         IOptions<IdentityOptions> options)
  5.     : RevalidatingServerAuthenticationStateProvider(loggerFactory)
  6. {
  7.     protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(30);
  8.     protected override async Task<bool> ValidateAuthenticationStateAsync(
  9.         AuthenticationState authenticationState, CancellationToken cancellationToken)
  10.     {
  11.         // Get the user manager from a new scope to ensure it fetches fresh data
  12.         await using var scope = scopeFactory.CreateAsyncScope();
  13.         var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
  14.         return await ValidateSecurityStampAsync(userManager, authenticationState.User);
  15.     }
  16.     private async Task<bool> ValidateSecurityStampAsync(UserManager<ApplicationUser> userManager, ClaimsPrincipal principal)
  17.     {
  18.         var user = await userManager.GetUserAsync(principal);
  19.         if (user is null)
  20.         {
  21.             return false;
  22.         }
  23.         else if (!userManager.SupportsUserSecurityStamp)
  24.         {
  25.             return true;
  26.         }
  27.         else
  28.         {
  29.             var principalStamp = principal.FindFirstValue(options.Value.ClaimsIdentity.SecurityStampClaimType);
  30.             var userStamp = await userManager.GetSecurityStampAsync(user);
  31.             return principalStamp == userStamp;
  32.         }
  33.     }
  34. }
复制代码
登录时,可以使用表单提交,也可以使用Ajax POST(制作动态网页时的首选),后端处理的逻辑代码相同,即都通过SignInManager实现发送Set-Cookie请求
表单处理:
  1.     public async Task LoginUser()
  2.     {
  3.             // This doesn't count login failures towards account lockout
  4.             // To enable password failures to trigger account lockout, set lockoutOnFailure: true
  5.             var result = await SignInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
  6.             if (result.Succeeded)
  7.             {
  8.                 RedirectManager.RedirectTo("/");
  9.             }
  10.             else if (result.RequiresTwoFactor)
  11.             {
  12.                 RedirectManager.RedirectTo(
  13.                     "Account/LoginWith2fa",
  14.                     new() { ["returnUrl"] = ReturnUrl, ["rememberMe"] = Input.RememberMe });
  15.             }
  16.             else if (result.IsLockedOut)
  17.             {
  18.                 RedirectManager.RedirectTo("Account/Lockout");
  19.             }
  20.             else
  21.             {
  22.                 errorMessage = $@"账号或密码错误";
  23.             }
  24.     }
复制代码
WebAPI:
  1. app.MapPost("Login", async (CheckDto Input,
  2.                             UserManager<ApplicationUser> userManager,
  3.                             SignInManager<ApplicationUser> signInManager) =>
  4. {
  5.     var emailResult = await userManager.FindByEmailAsync(dto.username);
  6.     if (emailResult is null) return Results.BadRequest("账号未注册");
  7.     if (await userManager.CheckPasswordAsync(emailResult, dto.password))
  8.     {
  9.         await signInManager.SignInAsync(emailResult, false);
  10.         return Results.Ok();
  11.     }
  12.     return Results.BadRequest("密码错误");  //401不能返回错误信息,故使用400
  13. });
复制代码
WebAssembly + Cookie + UserInfo Endpoint

此方式是微软推荐的鉴权方式,相比于JWT安全性较高
注册服务(使用.NET 8以后新增的方法)
  1. builder.Services.AddAuthorization();
  2. builder.Services.AddIdentityApiEndpoints<ApplicationUser>()
  3.     .AddEntityFrameworkStores<ApplicationDbContext>();
  4. var app = builder.Build();
  5. app.UseAuthentication();
  6. app.UseAuthorization();
  7. app.MapIdentityApi<ApplicationUser>();
复制代码
源码解读:
  1.     /// <summary>
  2.     /// Adds a set of common identity services to the application to support <see cref="IdentityApiEndpointRouteBuilderExtensions.MapIdentityApi{TUser}(IEndpointRouteBuilder)"/>
  3.     /// and configures authentication to support identity bearer tokens and cookies.
  4.     /// </summary>
  5.     /// <param name="services">The <see cref="IServiceCollection"/>.</param>
  6.     /// <param name="configure">Configures the <see cref="IdentityOptions"/>.</param>
  7.     /// <returns>The <see cref="IdentityBuilder"/>.</returns>
  8.     public static IdentityBuilder AddIdentityApiEndpoints<TUser>(this IServiceCollection services, Action<IdentityOptions> configure)
  9.         where TUser : class, new()
  10.     {
  11.         ArgumentNullException.ThrowIfNull(services);
  12.         ArgumentNullException.ThrowIfNull(configure);
  13.         services
  14.             .AddAuthentication(IdentityConstants.BearerAndApplicationScheme)
  15.             .AddScheme<AuthenticationSchemeOptions, CompositeIdentityHandler>(IdentityConstants.BearerAndApplicationScheme, null, compositeOptions =>
  16.             {
  17.                 compositeOptions.ForwardDefault = IdentityConstants.BearerScheme;
  18.                 compositeOptions.ForwardAuthenticate = IdentityConstants.BearerAndApplicationScheme;
  19.             })
  20.             .AddBearerToken(IdentityConstants.BearerScheme)
  21.             .AddIdentityCookies();
  22.         return services.AddIdentityCore<TUser>(configure)
  23.             .AddApiEndpoints();
  24.     }
  25.     /// <summary>
  26.     /// Add endpoints for registering, logging in, and logging out using ASP.NET Core Identity.
  27.     /// </summary>
  28.     /// <typeparam name="TUser">The type describing the user. This should match the generic parameter in <see cref="UserManager{TUser}"/>.</typeparam>
  29.     /// <param name="endpoints">
  30.     /// The <see cref="IEndpointRouteBuilder"/> to add the identity endpoints to.
  31.     /// Call <see cref="EndpointRouteBuilderExtensions.MapGroup(IEndpointRouteBuilder, string)"/> to add a prefix to all the endpoints.
  32.     /// </param>
  33.     /// <returns>An <see cref="IEndpointConventionBuilder"/> to further customize the added endpoints.</returns>
  34.     public static IEndpointConventionBuilder MapIdentityApi<TUser>(this IEndpointRouteBuilder endpoints)
  35.         where TUser : class, new()
  36.     {
  37.         ArgumentNullException.ThrowIfNull(endpoints);
  38.         var timeProvider = endpoints.ServiceProvider.GetRequiredService<TimeProvider>();
  39.         var bearerTokenOptions = endpoints.ServiceProvider.GetRequiredService<IOptionsMonitor<BearerTokenOptions>>();
  40.         var emailSender = endpoints.ServiceProvider.GetRequiredService<IEmailSender<TUser>>();
  41.         var linkGenerator = endpoints.ServiceProvider.GetRequiredService<LinkGenerator>();
  42.         // We'll figure out a unique endpoint name based on the final route pattern during endpoint generation.
  43.         string? confirmEmailEndpointName = null;
  44.         var routeGroup = endpoints.MapGroup("");
  45.         // NOTE: We cannot inject UserManager<TUser> directly because the TUser generic parameter is currently unsupported by RDG.
  46.         // https://github.com/dotnet/aspnetcore/issues/47338
  47.         routeGroup.MapPost("/register", async Task<Results<Ok, ValidationProblem>>
  48.             ([FromBody] RegisterRequest registration, HttpContext context, [FromServices] IServiceProvider sp) =>
  49.         {
  50.             var userManager = sp.GetRequiredService<UserManager<TUser>>();
  51.             if (!userManager.SupportsUserEmail)
  52.             {
  53.                 throw new NotSupportedException($"{nameof(MapIdentityApi)} requires a user store with email support.");
  54.             }
  55.             var userStore = sp.GetRequiredService<IUserStore<TUser>>();
  56.             var emailStore = (IUserEmailStore<TUser>)userStore;
  57.             var email = registration.Email;
  58.             if (string.IsNullOrEmpty(email) || !_emailAddressAttribute.IsValid(email))
  59.             {
  60.                 return CreateValidationProblem(IdentityResult.Failed(userManager.ErrorDescriber.InvalidEmail(email)));
  61.             }
  62.             var user = new TUser();
  63.             await userStore.SetUserNameAsync(user, email, CancellationToken.None);
  64.             await emailStore.SetEmailAsync(user, email, CancellationToken.None);
  65.             var result = await userManager.CreateAsync(user, registration.Password);
  66.             if (!result.Succeeded)
  67.             {
  68.                 return CreateValidationProblem(result);
  69.             }
  70.             await SendConfirmationEmailAsync(user, userManager, context, email);
  71.             return TypedResults.Ok();
  72.         });
  73.         routeGroup.MapPost("/login", async Task<Results<Ok<AccessTokenResponse>, EmptyHttpResult, ProblemHttpResult>>
  74.             ([FromBody] LoginRequest login, [FromQuery] bool? useCookies, [FromQuery] bool? useSessionCookies, [FromServices] IServiceProvider sp) =>
  75.         {
  76.             var signInManager = sp.GetRequiredService<SignInManager<TUser>>();
  77.             var useCookieScheme = (useCookies == true) || (useSessionCookies == true);
  78.             var isPersistent = (useCookies == true) && (useSessionCookies != true);
  79.             signInManager.AuthenticationScheme = useCookieScheme ? IdentityConstants.ApplicationScheme : IdentityConstants.BearerScheme;
  80.             var result = await signInManager.PasswordSignInAsync(login.Email, login.Password, isPersistent, lockoutOnFailure: true);
  81.             if (result.RequiresTwoFactor)
  82.             {
  83.                 if (!string.IsNullOrEmpty(login.TwoFactorCode))
  84.                 {
  85.                     result = await signInManager.TwoFactorAuthenticatorSignInAsync(login.TwoFactorCode, isPersistent, rememberClient: isPersistent);
  86.                 }
  87.                 else if (!string.IsNullOrEmpty(login.TwoFactorRecoveryCode))
  88.                 {
  89.                     result = await signInManager.TwoFactorRecoveryCodeSignInAsync(login.TwoFactorRecoveryCode);
  90.                 }
  91.             }
  92.             if (!result.Succeeded)
  93.             {
  94.                 return TypedResults.Problem(result.ToString(), statusCode: StatusCodes.Status401Unauthorized);
  95.             }
  96.             // The signInManager already produced the needed response in the form of a cookie or bearer token.
  97.             return TypedResults.Empty;
  98.         });
  99.         routeGroup.MapPost("/refresh", async Task<Results<Ok<AccessTokenResponse>, UnauthorizedHttpResult, SignInHttpResult, ChallengeHttpResult>>
  100.             ([FromBody] RefreshRequest refreshRequest, [FromServices] IServiceProvider sp) =>
  101.         {
  102.             var signInManager = sp.GetRequiredService<SignInManager<TUser>>();
  103.             var refreshTokenProtector = bearerTokenOptions.Get(IdentityConstants.BearerScheme).RefreshTokenProtector;
  104.             var refreshTicket = refreshTokenProtector.Unprotect(refreshRequest.RefreshToken);
  105.             // Reject the /refresh attempt with a 401 if the token expired or the security stamp validation fails
  106.             if (refreshTicket?.Properties?.ExpiresUtc is not { } expiresUtc ||
  107.                 timeProvider.GetUtcNow() >= expiresUtc ||
  108.                 await signInManager.ValidateSecurityStampAsync(refreshTicket.Principal) is not TUser user)
  109.             {
  110.                 return TypedResults.Challenge();
  111.             }
  112.             var newPrincipal = await signInManager.CreateUserPrincipalAsync(user);
  113.             return TypedResults.SignIn(newPrincipal, authenticationScheme: IdentityConstants.BearerScheme);
  114.         });
  115.         routeGroup.MapGet("/confirmEmail", async Task<Results<ContentHttpResult, UnauthorizedHttpResult>>
  116.             ([FromQuery] string userId, [FromQuery] string code, [FromQuery] string? changedEmail, [FromServices] IServiceProvider sp) =>
  117.         {
  118.             var userManager = sp.GetRequiredService<UserManager<TUser>>();
  119.             if (await userManager.FindByIdAsync(userId) is not { } user)
  120.             {
  121.                 // We could respond with a 404 instead of a 401 like Identity UI, but that feels like unnecessary information.
  122.                 return TypedResults.Unauthorized();
  123.             }
  124.             try
  125.             {
  126.                 code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
  127.             }
  128.             catch (FormatException)
  129.             {
  130.                 return TypedResults.Unauthorized();
  131.             }
  132.             IdentityResult result;
  133.             if (string.IsNullOrEmpty(changedEmail))
  134.             {
  135.                 result = await userManager.ConfirmEmailAsync(user, code);
  136.             }
  137.             else
  138.             {
  139.                 // As with Identity UI, email and user name are one and the same. So when we update the email,
  140.                 // we need to update the user name.
  141.                 result = await userManager.ChangeEmailAsync(user, changedEmail, code);
  142.                 if (result.Succeeded)
  143.                 {
  144.                     result = await userManager.SetUserNameAsync(user, changedEmail);
  145.                 }
  146.             }
  147.             if (!result.Succeeded)
  148.             {
  149.                 return TypedResults.Unauthorized();
  150.             }
  151.             return TypedResults.Text("Thank you for confirming your email.");
  152.         })
  153.         .Add(endpointBuilder =>
  154.         {
  155.             var finalPattern = ((RouteEndpointBuilder)endpointBuilder).RoutePattern.RawText;
  156.             confirmEmailEndpointName = $"{nameof(MapIdentityApi)}-{finalPattern}";
  157.             endpointBuilder.Metadata.Add(new EndpointNameMetadata(confirmEmailEndpointName));
  158.         });
  159.         routeGroup.MapPost("/resendConfirmationEmail", async Task<Ok>
  160.             ([FromBody] ResendConfirmationEmailRequest resendRequest, HttpContext context, [FromServices] IServiceProvider sp) =>
  161.         {
  162.             var userManager = sp.GetRequiredService<UserManager<TUser>>();
  163.             if (await userManager.FindByEmailAsync(resendRequest.Email) is not { } user)
  164.             {
  165.                 return TypedResults.Ok();
  166.             }
  167.             await SendConfirmationEmailAsync(user, userManager, context, resendRequest.Email);
  168.             return TypedResults.Ok();
  169.         });
  170.         routeGroup.MapPost("/forgotPassword", async Task<Results<Ok, ValidationProblem>>
  171.             ([FromBody] ForgotPasswordRequest resetRequest, [FromServices] IServiceProvider sp) =>
  172.         {
  173.             var userManager = sp.GetRequiredService<UserManager<TUser>>();
  174.             var user = await userManager.FindByEmailAsync(resetRequest.Email);
  175.             if (user is not null && await userManager.IsEmailConfirmedAsync(user))
  176.             {
  177.                 var code = await userManager.GeneratePasswordResetTokenAsync(user);
  178.                 code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
  179.                 await emailSender.SendPasswordResetCodeAsync(user, resetRequest.Email, HtmlEncoder.Default.Encode(code));
  180.             }
  181.             // Don't reveal that the user does not exist or is not confirmed, so don't return a 200 if we would have
  182.             // returned a 400 for an invalid code given a valid user email.
  183.             return TypedResults.Ok();
  184.         });
  185.         routeGroup.MapPost("/resetPassword", async Task<Results<Ok, ValidationProblem>>
  186.             ([FromBody] ResetPasswordRequest resetRequest, [FromServices] IServiceProvider sp) =>
  187.         {
  188.             var userManager = sp.GetRequiredService<UserManager<TUser>>();
  189.             var user = await userManager.FindByEmailAsync(resetRequest.Email);
  190.             if (user is null || !(await userManager.IsEmailConfirmedAsync(user)))
  191.             {
  192.                 // Don't reveal that the user does not exist or is not confirmed, so don't return a 200 if we would have
  193.                 // returned a 400 for an invalid code given a valid user email.
  194.                 return CreateValidationProblem(IdentityResult.Failed(userManager.ErrorDescriber.InvalidToken()));
  195.             }
  196.             IdentityResult result;
  197.             try
  198.             {
  199.                 var code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(resetRequest.ResetCode));
  200.                 result = await userManager.ResetPasswordAsync(user, code, resetRequest.NewPassword);
  201.             }
  202.             catch (FormatException)
  203.             {
  204.                 result = IdentityResult.Failed(userManager.ErrorDescriber.InvalidToken());
  205.             }
  206.             if (!result.Succeeded)
  207.             {
  208.                 return CreateValidationProblem(result);
  209.             }
  210.             return TypedResults.Ok();
  211.         });
  212.         var accountGroup = routeGroup.MapGroup("/manage").RequireAuthorization();
  213.         accountGroup.MapPost("/2fa", async Task<Results<Ok<TwoFactorResponse>, ValidationProblem, NotFound>>
  214.             (ClaimsPrincipal claimsPrincipal, [FromBody] TwoFactorRequest tfaRequest, [FromServices] IServiceProvider sp) =>
  215.         {
  216.             var signInManager = sp.GetRequiredService<SignInManager<TUser>>();
  217.             var userManager = signInManager.UserManager;
  218.             if (await userManager.GetUserAsync(claimsPrincipal) is not { } user)
  219.             {
  220.                 return TypedResults.NotFound();
  221.             }
  222.             if (tfaRequest.Enable == true)
  223.             {
  224.                 if (tfaRequest.ResetSharedKey)
  225.                 {
  226.                     return CreateValidationProblem("CannotResetSharedKeyAndEnable",
  227.                         "Resetting the 2fa shared key must disable 2fa until a 2fa token based on the new shared key is validated.");
  228.                 }
  229.                 if (string.IsNullOrEmpty(tfaRequest.TwoFactorCode))
  230.                 {
  231.                     return CreateValidationProblem("RequiresTwoFactor",
  232.                         "No 2fa token was provided by the request. A valid 2fa token is required to enable 2fa.");
  233.                 }
  234.                 if (!await userManager.VerifyTwoFactorTokenAsync(user, userManager.Options.Tokens.AuthenticatorTokenProvider, tfaRequest.TwoFactorCode))
  235.                 {
  236.                     return CreateValidationProblem("InvalidTwoFactorCode",
  237.                         "The 2fa token provided by the request was invalid. A valid 2fa token is required to enable 2fa.");
  238.                 }
  239.                 await userManager.SetTwoFactorEnabledAsync(user, true);
  240.             }
  241.             else if (tfaRequest.Enable == false || tfaRequest.ResetSharedKey)
  242.             {
  243.                 await userManager.SetTwoFactorEnabledAsync(user, false);
  244.             }
  245.             if (tfaRequest.ResetSharedKey)
  246.             {
  247.                 await userManager.ResetAuthenticatorKeyAsync(user);
  248.             }
  249.             string[]? recoveryCodes = null;
  250.             if (tfaRequest.ResetRecoveryCodes || (tfaRequest.Enable == true && await userManager.CountRecoveryCodesAsync(user) == 0))
  251.             {
  252.                 var recoveryCodesEnumerable = await userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
  253.                 recoveryCodes = recoveryCodesEnumerable?.ToArray();
  254.             }
  255.             if (tfaRequest.ForgetMachine)
  256.             {
  257.                 await signInManager.ForgetTwoFactorClientAsync();
  258.             }
  259.             var key = await userManager.GetAuthenticatorKeyAsync(user);
  260.             if (string.IsNullOrEmpty(key))
  261.             {
  262.                 await userManager.ResetAuthenticatorKeyAsync(user);
  263.                 key = await userManager.GetAuthenticatorKeyAsync(user);
  264.                 if (string.IsNullOrEmpty(key))
  265.                 {
  266.                     throw new NotSupportedException("The user manager must produce an authenticator key after reset.");
  267.                 }
  268.             }
  269.             return TypedResults.Ok(new TwoFactorResponse
  270.             {
  271.                 SharedKey = key,
  272.                 RecoveryCodes = recoveryCodes,
  273.                 RecoveryCodesLeft = recoveryCodes?.Length ?? await userManager.CountRecoveryCodesAsync(user),
  274.                 IsTwoFactorEnabled = await userManager.GetTwoFactorEnabledAsync(user),
  275.                 IsMachineRemembered = await signInManager.IsTwoFactorClientRememberedAsync(user),
  276.             });
  277.         });
  278.         accountGroup.MapGet("/info", async Task<Results<Ok<InfoResponse>, ValidationProblem, NotFound>>
  279.             (ClaimsPrincipal claimsPrincipal, [FromServices] IServiceProvider sp) =>
  280.         {
  281.             var userManager = sp.GetRequiredService<UserManager<TUser>>();
  282.             if (await userManager.GetUserAsync(claimsPrincipal) is not { } user)
  283.             {
  284.                 return TypedResults.NotFound();
  285.             }
  286.             return TypedResults.Ok(await CreateInfoResponseAsync(user, userManager));
  287.         });
  288.         accountGroup.MapPost("/info", async Task<Results<Ok<InfoResponse>, ValidationProblem, NotFound>>
  289.             (ClaimsPrincipal claimsPrincipal, [FromBody] InfoRequest infoRequest, HttpContext context, [FromServices] IServiceProvider sp) =>
  290.         {
  291.             var userManager = sp.GetRequiredService<UserManager<TUser>>();
  292.             if (await userManager.GetUserAsync(claimsPrincipal) is not { } user)
  293.             {
  294.                 return TypedResults.NotFound();
  295.             }
  296.             if (!string.IsNullOrEmpty(infoRequest.NewEmail) && !_emailAddressAttribute.IsValid(infoRequest.NewEmail))
  297.             {
  298.                 return CreateValidationProblem(IdentityResult.Failed(userManager.ErrorDescriber.InvalidEmail(infoRequest.NewEmail)));
  299.             }
  300.             if (!string.IsNullOrEmpty(infoRequest.NewPassword))
  301.             {
  302.                 if (string.IsNullOrEmpty(infoRequest.OldPassword))
  303.                 {
  304.                     return CreateValidationProblem("OldPasswordRequired",
  305.                         "The old password is required to set a new password. If the old password is forgotten, use /resetPassword.");
  306.                 }
  307.                 var changePasswordResult = await userManager.ChangePasswordAsync(user, infoRequest.OldPassword, infoRequest.NewPassword);
  308.                 if (!changePasswordResult.Succeeded)
  309.                 {
  310.                     return CreateValidationProblem(changePasswordResult);
  311.                 }
  312.             }
  313.             if (!string.IsNullOrEmpty(infoRequest.NewEmail))
  314.             {
  315.                 var email = await userManager.GetEmailAsync(user);
  316.                 if (email != infoRequest.NewEmail)
  317.                 {
  318.                     await SendConfirmationEmailAsync(user, userManager, context, infoRequest.NewEmail, isChange: true);
  319.                 }
  320.             }
  321.             return TypedResults.Ok(await CreateInfoResponseAsync(user, userManager));
  322.         });
  323.     }
复制代码
可以看到,基架生成的info接口返回的用户信息非常有限,实际业务中需要自行写一个返回角色/Claims信息的userinfo接口(注入UserManager和RoleManager查询)
根据基架生成的API,编写前端代码:
注册服务:
  1. // 注册LocalStorage服务
  2. builder.Services.AddBlazoredLocalStorageAsSingleton();
  3. // 注册鉴权服务
  4. builder.Services.AddSingleton<AuthenticationStateProvider, CookieAuthenticationStateProvider>();
  5. // 注册通用客户端的鉴权拦截器(令牌过期重试)
  6. builder.Services.AddSingleton<AuthenticationStateHandler>();
  7. // 注册鉴权专用客户端
  8. builder.Services.AddHttpClient("auth", client =>
  9. {
  10.     client.BaseAddress = new Uri("API_URL");
  11. });
  12. // 注册业务通用客户端
  13. builder.Services.AddHttpClient("backend", client =>
  14. {
  15.     client.BaseAddress = new Uri("API_URL");
  16. }).AddHttpMessageHandler<AuthenticationStateHandler>();
  17. // 设为默认客户端
  18. builder.Services.AddSingleton(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("backend"));
  19. // 注册鉴权基架
  20. builder.Services.AddAuthorizationCore();
  21. builder.Services.AddCascadingAuthenticationState();
复制代码
AuthenticationStateHandler:
  1. public class AuthenticationStateHandler(AuthenticationStateProvider stateProvider, NavigationManager navigationManager) : DelegatingHandler
  2. {
  3.     protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
  4.     {
  5.         var response = await base.SendAsync(request, cancellationToken);
  6.         //如果令牌过期,刷新令牌并重试请求
  7.         if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
  8.         {
  9.             var authState = await stateProvider.GetAuthenticationStateAsync();
  10.             if (authState.User.Identity?.IsAuthenticated ?? false)
  11.             {
  12.                 if (await (stateProvider as CookieAuthenticationStateProvider).RefreshTokenAsync())
  13.                 {
  14.                     return await SendAsync(request, cancellationToken);
  15.                 }
  16.             }
  17.             navigationManager.NavigateTo("/login");
  18.         }
  19.         return response;
  20.     }
  21. }
复制代码
CookieAuthenticationStateProvider:
  1. public sealed class CookieAuthenticationStateProvider(IServiceProvider serviceProvider, IHttpClientFactory httpClientFactory, ILocalStorageService localStorage, ISyncLocalStorageService syncLocalStorage) : AuthenticationStateProvider
  2. {
  3.     //token过期时间
  4.     private static TimeSpan UserCacheRefreshInterval = TimeSpan.FromHours(1);
  5.     //上次获取token时间
  6.     private static DateTimeOffset UserLastCheckTime = DateTimeOffset.FromUnixTimeSeconds(0);
  7.     //缓存用户状态
  8.     private ClaimsPrincipal CachedUser = new(new ClaimsIdentity());
  9.     //默认用户状态(未登录)
  10.     private static readonly Task<AuthenticationState> defaultUnanthenticatedTask = Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));
  11.     //刷新令牌
  12.     private string? refresh_token { get; set; } = syncLocalStorage.GetItem<string>("refresh_token");
  13.     //访问令牌
  14.     private string? access_token { get; set; } = syncLocalStorage.GetItem<string>("access_token");
  15.     //鉴权专用客户端示例
  16.     private HttpClient client = httpClientFactory.CreateClient("auth");
  17.     //解析令牌获取身份信息
  18.     private async Task ParseTokenAsync()
  19.     {   
  20.         var response = await client.GetAsync("/info");  //推荐自己写userinfo接口代替
  21.         if (response.IsSuccessStatusCode)
  22.         {
  23.             var infoResponse = await response.Content.ReadFromJsonAsync<InfoResponse>();
  24.             if (infoResponse != null)
  25.             {
  26.                 var claims = new List<Claim>
  27.                 {
  28.                     new Claim(ClaimTypes.Email, infoResponse.Email),
  29.                     new Claim("IsEmailConfirmed", infoResponse.IsEmailConfirmed.ToString())
  30.                 };
  31.             CachedUser = new ClaimsPrincipal(new ClaimsIdentity(claims, "Bearer"));
  32.             }
  33.         }
  34.         else
  35.         {
  36.             CachedUser = new ClaimsPrincipal(new ClaimsIdentity());
  37.         }
  38.     }
  39.     //设置客户端携带令牌
  40.     private void SetClientToken()
  41.     {
  42.         client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", access_token);
  43.         serviceProvider.GetRequiredService<HttpClient>().DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", access_token);
  44.     }
  45.     //处理令牌接口返回值
  46.     private async Task<bool> ParseResponseAsync(AccessTokenResponse token)
  47.     {
  48.         if (token != null)
  49.         {
  50.             refresh_token = token.RefreshToken;
  51.             access_token = token.AccessToken;
  52.             await localStorage.SetItemAsync("access_token", access_token);
  53.             await localStorage.SetItemAsync("refresh_token", refresh_token);
  54.             UserCacheRefreshInterval = TimeSpan.FromSeconds(token.ExpiresIn);
  55.             UserLastCheckTime = DateTimeOffset.UtcNow;
  56.             SetClientToken();
  57.             await ParseTokenAsync();
  58.             NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
  59.             return true;
  60.         }
  61.         return false;
  62.     }
  63.     //注册
  64.     public async Task<RegisterResponse> RegisterAsync(RegisterModel model)
  65.     {
  66.         var response = await client.PostAsJsonAsync(@"register", model);
  67.         var reg = await response.Content.ReadFromJsonAsync<RegisterResponse>();
  68.         if (reg.Succeeded) await ParseResponseAsync(reg.TokenResponse);
  69.         return reg;
  70.     }
  71.     //登录
  72.     public async Task<bool> LoginAsync(string username, string password)
  73.     {
  74.         var response = await client.PostAsJsonAsync(@"login", new LoginRequest { Username = username, Password = password } );
  75.         if (response.StatusCode == HttpStatusCode.Unauthorized)
  76.         {
  77.             return false;
  78.         }
  79.         var token = await response.Content.ReadFromJsonAsync<AccessTokenResponse>();
  80.         return await ParseResponseAsync(token);
  81.     }
  82.     //登出
  83.     public async Task LogoutAsync()
  84.     {
  85.         await client.PostAsync(@"logout",new StringContent(string.Empty));
  86.         refresh_token = null;
  87.         access_token = null;
  88.         await localStorage.RemoveItemAsync("access_token");
  89.         await localStorage.RemoveItemAsync("refresh_token");
  90.         UserLastCheckTime = DateTimeOffset.FromUnixTimeSeconds(0);
  91.         CachedUser = new ClaimsPrincipal(new ClaimsIdentity());
  92.         NotifyAuthenticationStateChanged(defaultUnanthenticatedTask);
  93.     }
  94.     //刷新令牌
  95.     public async Task<bool> RefreshTokenAsync()
  96.     {
  97.         if (refresh_token is null) return false;
  98.         SetClientToken();
  99.         var response = await client.PostAsJsonAsync(@"refresh", new { RefreshToken = refresh_token });
  100.         if (response.StatusCode == HttpStatusCode.Unauthorized)
  101.         {
  102.             return false;
  103.         }
  104.         var token = await response.Content.ReadFromJsonAsync<AccessTokenResponse>();
  105.         return await ParseResponseAsync(token);
  106.     }
  107.     //获取用户鉴权信息
  108.     public override async Task<AuthenticationState> GetAuthenticationStateAsync()
  109.     {
  110.         if (DateTimeOffset.UtcNow - UserLastCheckTime < UserCacheRefreshInterval || await RefreshTokenAsync())
  111.         {
  112.             return new AuthenticationState(CachedUser);
  113.         }
  114.         return await defaultUnanthenticatedTask;
  115.     }
  116. }
复制代码
WebAssembly + JWT

此方法安全性较低,不推荐
注册服务
  1. // JWT 配置
  2. var jwtSettings = builder.Configuration.GetSection("JwtSettings");
  3. var secretKey = Encoding.UTF8.GetBytes(jwtSettings["SecretKey"]!);
  4. // 添加认证服务
  5. builder.Services.AddAuthentication(options =>
  6. {
  7.     options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  8.     options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  9. })
  10. .AddJwtBearer(options =>
  11. {
  12.     options.TokenValidationParameters = new TokenValidationParameters
  13.     {
  14.         ValidateIssuer = true,
  15.         ValidateAudience = true,
  16.         ValidateLifetime = true,
  17.         ValidateIssuerSigningKey = true,
  18.         ValidIssuer = jwtSettings["Issuer"],
  19.         ValidAudience = jwtSettings["Audience"],
  20.         IssuerSigningKey = new SymmetricSecurityKey(secretKey)
  21.     };
  22. });
  23. // 添加授权服务
  24. builder.Services.AddAuthorization();
  25. // 添加 JWT 服务
  26. builder.Services.AddScoped<JwtService>();
  27. // 添加 Identity 服务(如果需要)
  28. builder.Services.AddIdentityCore<ApplicationUser>(options =>
  29. {
  30.     options.Password.RequireDigit = false;
  31.     options.Password.RequireLowercase = false;
  32.     options.Password.RequireNonAlphanumeric = false;
  33.     options.Password.RequireUppercase = false;
  34.     options.Password.RequiredLength = 6;
  35.     options.SignIn.RequireConfirmedEmail = false;
  36. }).AddRoles<IdentityRole<Guid>>()
  37.     .AddEntityFrameworkStores<ApplicationDbContext>()
  38.     .AddDefaultTokenProviders()
  39.     .AddRoleManager<RoleManager<IdentityRole<Guid>>>()
  40.     .AddUserManager<UserManager<ApplicationUser>>();
  41. var app = builder.Build();
  42. app.UseAuthentication();
  43. app.UseAuthorization();
复制代码
appsettings.json
  1.   "JwtSettings": {
  2.     "SecretKey": "your-very-looong-secret-key-here",
  3.     "Issuer": "your-issuer",
  4.     "Audience": "your-audience"
  5.   }
复制代码
JwtService
  1. public class JwtService(IConfiguration configuration)
  2. {
  3.     public AccessTokenResponse GenerateTokens(ApplicationUser user, IList<string> roles)
  4.     {
  5.         // 生成访问令牌
  6.         var accessToken = GenerateAccessToken(user, roles);
  7.         // 生成刷新令牌
  8.         var refreshToken = GenerateRefreshToken();
  9.         // 计算过期时间(以秒为单位)
  10.         var expiresIn = Convert.ToInt32(TimeSpan.FromHours(1).TotalSeconds);
  11.         return new AccessTokenResponse(accessToken, expiresIn, refreshToken);
  12.     }
  13.     private string GenerateAccessToken(ApplicationUser user, IList<string> roles)
  14.     {
  15.         var secretKey = Encoding.UTF8.GetBytes(configuration["JwtSettings:SecretKey"]!);
  16.         var signingCredentials = new SigningCredentials(
  17.             new SymmetricSecurityKey(secretKey),
  18.             SecurityAlgorithms.HmacSha256Signature
  19.         );
  20.         var claims = new List<Claim>
  21.     {
  22.         new(ClaimTypes.NameIdentifier, user.Id.ToString()),
  23.         new(ClaimTypes.Name, user.UserName!)
  24.     };
  25.         claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));
  26.         var token = new JwtSecurityToken(
  27.             issuer: configuration["JwtSettings:Issuer"],
  28.             audience: configuration["JwtSettings:Audience"],
  29.             claims: claims,
  30.             expires: DateTime.UtcNow.AddHours(1),
  31.             signingCredentials: signingCredentials
  32.         );
  33.         return new JwtSecurityTokenHandler().WriteToken(token);
  34.     }
  35.     private string GenerateRefreshToken()
  36.     {
  37.         var randomNumber = new byte[64];
  38.         using var rng = RandomNumberGenerator.Create();
  39.         rng.GetBytes(randomNumber);
  40.         return Convert.ToBase64String(randomNumber);
  41.     }
  42.     public ClaimsPrincipal? GetPrincipalFromExpiredToken(string token)
  43.     {
  44.         var secretKey = configuration["JwtSettings:SecretKey"]!;
  45.         var tokenValidationParameters = new TokenValidationParameters
  46.         {
  47.             ValidateIssuer = true,
  48.             ValidateAudience = true,
  49.             ValidateLifetime = false, // 不验证过期时间
  50.             ValidateIssuerSigningKey = true,
  51.             ValidIssuer = configuration["JwtSettings:Issuer"],
  52.             ValidAudience = configuration["JwtSettings:Audience"],
  53.             IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey))
  54.         };
  55.         var tokenHandler = new JwtSecurityTokenHandler();
  56.         var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken securityToken);
  57.         if (securityToken is not JwtSecurityToken jwtSecurityToken ||
  58.             !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256Signature,
  59.             StringComparison.InvariantCultureIgnoreCase))
  60.         {
  61.             return null;
  62.         }
  63.         return principal;
  64.     }
  65. }
复制代码
IdentityEndpoints
  1.     public static void MapIdentityEndpoints(this IEndpointRouteBuilder routes)
  2.     {
  3.         var group = routes.MapGroup("/Account").WithTags("Account");
  4.         group.MapPost("/Login", async (
  5.         LoginRequest model,
  6.         UserManager<ApplicationUser> userManager,
  7.         JwtService jwtService) =>
  8.         {
  9.             var user = await userManager.FindByNameAsync(model.Username);
  10.             if (user == null)
  11.             {
  12.                 return Results.Unauthorized();
  13.             }
  14.             var isPasswordValid = await userManager.CheckPasswordAsync(user, model.Password);
  15.             if (!isPasswordValid)
  16.             {
  17.                 return Results.Unauthorized();
  18.             }
  19.             var roles = await userManager.GetRolesAsync(user);
  20.             var tokenResponse = jwtService.GenerateTokens(user, roles);
  21.             // 保存刷新令牌到用户记录
  22.             user.RefreshToken = tokenResponse.RefreshToken;
  23.             user.RefreshTokenExpiryTime = DateTime.UtcNow.AddDays(7); // 刷新令牌7天有效
  24.             await userManager.UpdateAsync(user);
  25.             return Results.Ok(tokenResponse);
  26.         })
  27.         .AllowAnonymous()
  28.         .WithName("Login")
  29.         .WithOpenApi();
  30.         group.MapGet("/User", (HttpContext context) =>
  31.         {
  32.             var user = context.User;
  33.             return Results.Ok(new
  34.             {
  35.                 Username = user.Identity?.Name,
  36.                 UserId = user.FindFirst(ClaimTypes.NameIdentifier)?.Value,
  37.                 Roles = user.Claims
  38.                     .Where(c => c.Type == ClaimTypes.Role)
  39.                     .Select(c => c.Value)
  40.                     .ToList()
  41.             });
  42.         })
  43.         .RequireAuthorization()
  44.         .WithName("User")
  45.         .WithOpenApi();
  46.         group.MapPost("/Refresh", async (
  47.                       RefreshTokenModel model,
  48.                       UserManager<ApplicationUser> userManager,
  49.                       JwtService jwtService,
  50.                       HttpContext context) =>
  51.         {
  52.             // 从请求头获取过期的访问令牌
  53.             string? accessToken = context.Request.Headers["Authorization"]
  54.                 .FirstOrDefault()?.Split(" ").Last();
  55.             if (string.IsNullOrEmpty(accessToken))
  56.             {
  57.                 return Results.BadRequest("Access token is required");
  58.             }
  59.             // 从过期的访问令牌中获取用户信息
  60.             var principal = jwtService.GetPrincipalFromExpiredToken(accessToken);
  61.             if (principal == null)
  62.             {
  63.                 return Results.BadRequest("Invalid access token");
  64.             }
  65.             var username = principal.Identity?.Name;
  66.             var user = await userManager.FindByNameAsync(username!);
  67.             if (user == null ||
  68.                 user.RefreshToken != model.RefreshToken ||
  69.                 user.RefreshTokenExpiryTime <= DateTime.UtcNow)
  70.             {
  71.                 return Results.BadRequest("Invalid refresh token");
  72.             }
  73.             // 生成新的令牌
  74.             var roles = await userManager.GetRolesAsync(user);
  75.             var newTokenResponse = jwtService.GenerateTokens(user, roles);
  76.             // 更新数据库中的刷新令牌
  77.             user.RefreshToken = newTokenResponse.RefreshToken;
  78.             user.RefreshTokenExpiryTime = DateTime.UtcNow.AddDays(7);
  79.             await userManager.UpdateAsync(user);
  80.             return Results.Ok(newTokenResponse);
  81.         })
  82.         .AllowAnonymous()
  83.         .WithName("Refresh")
  84.         .WithOpenApi(); ;
  85.         group.MapPost("/Logout", async (
  86.                       UserManager<ApplicationUser> userManager,
  87.                       HttpContext context) =>
  88.          {
  89.              var user = context.User;
  90.              var appUser = await userManager.FindByNameAsync(user.Identity?.Name!);
  91.              if (appUser == null)
  92.              {
  93.                  return Results.NotFound();
  94.              }
  95.              // 清除刷新令牌
  96.              appUser.RefreshToken = null;
  97.              appUser.RefreshTokenExpiryTime = null;
  98.              await userManager.UpdateAsync(appUser);
  99.              return Results.Ok();
  100.          })
  101.         .RequireAuthorization()
  102.         .WithName("Logout")
  103.         .WithOpenApi();
  104.         group.MapPost("/Register", async (
  105.                       RegisterModel model,
  106.                       UserManager<ApplicationUser> userManager,
  107.                       JwtService jwtService) =>
  108.         {
  109.             // 验证模型
  110.             if (model.Password != model.ConfirmPassword)
  111.             {
  112.                 return Results.BadRequest(new RegisterResponse(
  113.                     false,
  114.                     ["密码和确认密码不匹配"], null, null
  115.                 ));
  116.             }
  117.             // 检查用户名是否已存在
  118.             var existingUser = await userManager.FindByNameAsync(model.Username);
  119.             if (existingUser != null)
  120.             {
  121.                 return Results.BadRequest(new RegisterResponse(
  122.                     false,
  123.                     ["用户名已存在"], null, null
  124.                 ));
  125.             }
  126.             // 检查邮箱是否已存在
  127.             var existingEmail = await userManager.FindByEmailAsync(model.Email);
  128.             if (existingEmail != null)
  129.             {
  130.                 return Results.BadRequest(new RegisterResponse(
  131.                     false,
  132.                     ["邮箱已被使用"], null, null
  133.                 ));
  134.             }
  135.             // 创建新用户
  136.             var user = new ApplicationUser
  137.             {
  138.                 UserName = model.Username,
  139.                 Email = model.Email,
  140.                 EmailConfirmed = true // 如果需要邮箱验证,设置为 false
  141.             };
  142.             // 添加用户
  143.             var result = await userManager.CreateAsync(user, model.Password);
  144.             if (!result.Succeeded)
  145.             {
  146.                 return Results.BadRequest(new RegisterResponse(
  147.                     false,
  148.                     result.Errors.Select(e => e.Description), null, null
  149.                 ));
  150.             }
  151.             // 添加默认角色
  152.             // await userManager.AddToRoleAsync(user, "User");
  153.             // 生成令牌
  154.             var roles = await userManager.GetRolesAsync(user);
  155.             var tokenResponse = jwtService.GenerateTokens(user, roles);
  156.             // 保存刷新令牌
  157.             user.RefreshToken = tokenResponse.RefreshToken;
  158.             user.RefreshTokenExpiryTime = DateTime.UtcNow.AddDays(7);
  159.             await userManager.UpdateAsync(user);
  160.             // 返回成功响应和令牌
  161.             return Results.Ok(new RegisterResponse(true, [], tokenResponse, "注册成功"));
  162.         })
  163.         .AllowAnonymous()
  164.         .WithName("Register")
  165.         .WithOpenApi();
  166.     }
复制代码
前端只需要修改上一案例中的ParseTokenAsync方法
  1.         private async Task ParseTokenAsync()
  2.         {
  3.             var handler = new JwtSecurityTokenHandler();
  4.             var token = handler.ReadJwtToken(access_token);
  5.             CachedUser = new ClaimsPrincipal(new ClaimsIdentity(token.Claims, "Bearer"));
  6.         }
复制代码
结语

详细案例文章、视频、源码请等候后续发布

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

忿忿的泥巴坨

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表