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

ASP.NET Core应用中Azure AD B2C仅登录认证实现及用户创建问询

ASP.NET Core + Azure AD B2C 仅登录策略配置与Graph用户管理实现

一、配置Azure AD B2C纯登录策略

  1. 在Azure Portal的B2C租户中,进入用户流,创建新的登录类型用户流(避免选择“注册和登录”类型)。
  2. 配置流的基本属性时,仅启用你需要的身份验证方式(比如本地账户登录),无需勾选任何注册相关选项。
  3. 完成流创建后,记录该策略的ID(格式通常为B2C_1_signin),后续ASP.NET Core配置会用到。

二、通过Microsoft Graph创建B2C用户(支持首次登录重置密码)

1. 配置Graph API权限

在你的B2C应用注册中:

  • 进入API权限,点击添加权限,选择Microsoft Graph → 应用权限。
  • 添加User.ReadWrite.All权限,点击授予管理员同意(需持有租户管理员权限)。

2. 安装依赖包

在ASP.NET Core项目中执行以下命令安装Microsoft Graph相关SDK:

dotnet add package Microsoft.Graph
dotnet add package Microsoft.Identity.Client

3. 初始化Graph客户端

在Program.cs中配置Graph客户端实例(采用客户端凭据流完成认证):

builder.Services.AddSingleton<GraphServiceClient>(sp =>
{
    var tenantId = builder.Configuration["AzureAdB2C:TenantId"];
    var clientId = builder.Configuration["AzureAdB2C:ClientId"];
    var clientSecret = builder.Configuration["AzureAdB2C:ClientSecret"];

    var clientCredential = new ClientCredential(clientSecret);
    var authority = $"https://login.microsoftonline.com/{tenantId}/v2.0";

    var authProvider = new ClientCredentialProvider(clientCredential, authority);
    return new GraphServiceClient(authProvider);
});

4. 创建用户的代码示例

编写服务类实现用户创建逻辑,核心是设置forceChangePasswordNextSignIn: true,确保用户首次登录必须重置密码:

public class B2CUserService
{
    private readonly GraphServiceClient _graphClient;
    private readonly string _b2cDomain = "your-b2c-tenant.onmicrosoft.com"; // 替换为你的B2C租户域名

    public B2CUserService(GraphServiceClient graphClient)
    {
        _graphClient = graphClient;
    }

    public async Task<User> CreateB2CUserAsync(string email, string displayName, string initialPassword)
    {
        var user = new User
        {
            DisplayName = displayName,
            AccountEnabled = true,
            UserPrincipalName = $"{email.Split('@')[0]}@{_b2cDomain}",
            MailNickname = email.Split('@')[0],
            PasswordProfile = new PasswordProfile
            {
                Password = initialPassword,
                ForceChangePasswordNextSignIn = true
            },
            PasswordPolicies = "DisablePasswordExpiration" // 可选:禁用密码过期规则
        };

        return await _graphClient.Users
            .Request()
            .AddAsync(user);
    }
}

注意:初始密码需符合Azure AD B2C的默认密码复杂度要求(至少8字符,包含大小写字母、数字、特殊字符)。

三、ASP.NET Core 认证配置(绑定纯登录策略)

在Program.cs中配置Azure AD B2C认证,仅指定登录策略:

builder.Services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
    .AddAzureADB2C(options =>
    {
        builder.Configuration.Bind("AzureAdB2C", options);
        options.SignInPolicyId = "B2C_1_signin"; // 替换为你创建的登录策略ID
        // 无需设置SignUpPolicyId,确保仅启用登录流程
    });

builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = options.DefaultPolicy;
});

builder.Services.AddRazorPages();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapRazorPages();
app.Run();

对应的appsettings.json配置示例:

{
  "AzureAdB2C": {
    "Instance": "https://your-b2c-tenant.b2clogin.com/",
    "Domain": "your-b2c-tenant.onmicrosoft.com",
    "TenantId": "your-tenant-guid",
    "ClientId": "your-app-client-id",
    "ClientSecret": "your-app-client-secret",
    "SignInPolicyId": "B2C_1_signin"
  }
}

四、首次登录重置密码流程说明

当用户首次使用初始密码登录时,Azure AD B2C会自动拦截登录请求,跳转到内置的密码重置页面,要求用户设置新密码。完成重置后,用户才能正常进入应用。此流程无需额外开发前端或后端逻辑,由B2C策略自动处理。

内容的提问来源于stack exchange,提问作者ANIKET JHA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 06:21:00