You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 18:16:02