如何在ASP.NET Core Identity中使用EF创建自定义Azure AD允许账户表
实现指定Azure AD账户登录校验的方案
1. 创建允许登录的Azure AD账户实体类
新建实体类存储允许的账户信息,优先用Azure AD用户的唯一ObjectId作为校验标识,也可搭配邮箱便于管理:
public class AllowedAzureAdUser { public int Id { get; set; } public string ObjectId { get; set; } = string.Empty; public string Email { get; set; } = string.Empty; }
2. 将实体添加到DbContext
把上述实体注册到你的Identity DbContext中:
public class AppDbContext : IdentityDbContext<IdentityUser> { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<AllowedAzureAdUser> AllowedAzureAdUsers { get; set; } }
3. 生成并执行数据库迁移
通过命令行创建迁移并同步到数据库:
# 终端命令 dotnet ef migrations add AddAllowedAzureAdUsersTable dotnet ef database update # Package Manager Console命令 Add-Migration AddAllowedAzureAdUsersTable Update-Database
4. 拦截Azure AD登录流程做校验
自定义OpenIdConnectEvents拦截登录回调,校验当前用户是否在允许列表内:
services.AddAuthentication() .AddAzureAD(options => Configuration.Bind("AzureAd", options)) .AddCookie(); services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options => { options.Events = new OpenIdConnectEvents { OnTokenValidated = async context => { var objectId = context.Principal.FindFirstValue(ClaimTypes.NameIdentifier); if (string.IsNullOrEmpty(objectId)) { context.Fail("无法获取Azure AD用户标识"); return; } var dbContext = context.HttpContext.RequestServices.GetRequiredService<AppDbContext>(); var isAllowed = await dbContext.AllowedAzureAdUsers .AnyAsync(u => u.ObjectId == objectId); if (!isAllowed) { context.Fail("该Azure AD账户未被授权登录"); return; } await Task.CompletedTask; } }; });
5. 管理允许登录的账户
通过后台管理页面或直接操作数据库,将授权的Azure AD用户ObjectId和邮箱录入AllowedAzureAdUsers表即可。
注意:优先用
ObjectId作为校验依据,它是Azure AD用户的唯一标识,比邮箱更可靠,避免因邮箱变更或大小写问题导致校验失败。
内容的提问来源于stack exchange,提问作者Hoang Minh
相关产品推荐
相关产品推荐

