如何为已集成Microsoft Identity的Blazor WebAssembly应用添加Identity账户
整合Microsoft Identity与ASP.NET Core Identity到.NET 7 Blazor WebAssembly应用
以下是实现两种认证方式共存的具体步骤:
1. 后端Server项目配置ASP.NET Core Identity
- 安装必要NuGet包:
Microsoft.AspNetCore.Identity.EntityFrameworkCore、对应数据库提供商包(如Microsoft.EntityFrameworkCore.SqlServer) - 在
Program.cs中添加Identity服务与数据库上下文:// 添加数据库上下文 builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); // 配置Identity builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>(); - 创建
ApplicationDbContext类:public class ApplicationDbContext : IdentityDbContext<IdentityUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } } - 在
appsettings.json中添加数据库连接字符串:"ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=BlazorAuthDb;Trusted_Connection=True;MultipleActiveResultSets=true" } - 执行迁移命令初始化数据库:
Add-Migration InitialCreate Update-Database
2. 调整后端认证中间件顺序
在Program.cs中确保认证中间件支持两种认证方式,顺序正确:
// 保留原有Azure AD API认证配置 builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd")); // 添加Identity Cookie认证与Azure AD Web App认证 builder.Services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = "AzureAD"; // 默认跳转Azure AD登录,可按需修改 }) .AddCookie() .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"), "AzureAD", "AzureADCookie"); // 认证、授权中间件顺序不能错 app.UseAuthentication(); app.UseAuthorization();
3. 前端Blazor WASM项目配置双认证支持
在Program.cs中同时配置MSAL(Azure AD)与Cookie(Identity)认证:
// Azure AD认证配置 builder.Services.AddMsalAuthentication(options => { builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication); options.ProviderOptions.DefaultAccessTokenScopes.Add("api://{你的API标识}/access_as_user"); }); // Identity Cookie认证支持 builder.Services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = "Msal"; // 可根据需求调整默认登录入口 }) .AddCookie();
4. 后端添加Identity账户管理API
创建AccountController处理本地账户的注册、登录、登出:
[ApiController] [Route("api/[controller]")] public class AccountController : ControllerBase { private readonly UserManager<IdentityUser> _userManager; private readonly SignInManager<IdentityUser> _signInManager; public AccountController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager) { _userManager = userManager; _signInManager = signInManager; } [HttpPost("register")] public async Task<IActionResult> Register([FromBody] RegisterModel model) { var user = new IdentityUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return Ok(); } return BadRequest(result.Errors); } [HttpPost("login")] public async Task<IActionResult> Login([FromBody] LoginModel model) { var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { return Ok(); } return Unauthorized(); } [HttpPost("logout")] public async Task<IActionResult> Logout() { await _signInManager.SignOutAsync(); return Ok(); } } // 配套Model类 public class RegisterModel { public string Email { get; set; } public string Password { get; set; } } public class LoginModel { public string Email { get; set; } public string Password { get; set; } public bool RememberMe { get; set; } }
5. 前端添加双登录入口
创建自定义登录页面,提供两个选项:
- 公司账户登录:调用MSAL的
LoginAsync方法触发Azure AD登录流程 - 本地账户登录/注册:通过HTTP请求调用后端
AccountController的对应接口完成操作
6. 授权逻辑区分(可选)
若需区分内部Azure AD用户与外部本地用户,可通过用户声明判断:
- Azure AD用户会包含
http://schemas.microsoft.com/identity/claims/tenantid等专属声明 - 本地Identity用户仅包含默认的Identity声明(如
nameidentifier、email)
内容的提问来源于stack exchange,提问作者ArcDotNet
相关产品推荐
相关产品推荐

