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

Blazor WASM与Azure AD认证授权已实现,需配置SSO免手动登录求指引

实现Blazor WASM与Azure AD的SSO自动登录

核心配置调整

1. Blazor WASM客户端自动触发登录

在Program.cs中修改身份验证服务配置,添加自动登录逻辑:

builder.Services.AddMsalAuthentication(options =>
{
    builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
    options.ProviderOptions.DefaultAccessTokenScopes.Add("api://{你的API应用ID}/access_as_user");
    options.AuthenticationPaths.LogInPath = "/authentication/login";
})
.AddAccountClaimsPrincipalFactory<CustomUserFactory>();

// 启动时自动检查登录状态
var app = builder.Build();
var navigationManager = app.Services.GetRequiredService<NavigationManager>();
var authStateProvider = app.Services.GetRequiredService<AuthenticationStateProvider>();

var authState = await authStateProvider.GetAuthenticationStateAsync();
if (!authState.User.Identity.IsAuthenticated)
{
    navigationManager.NavigateTo("/authentication/login");
}

同时修改Authentication.razor组件,初始化时直接触发登录流程:

@page "/authentication/{action}"
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@inject NavigationManager Navigation

@code {
    [Parameter] public string Action { get; set; }

    protected override async Task OnInitializedAsync()
    {
        if (Action == "login")
        {
            var authService = ScopedServices.GetRequiredService<IAccessTokenProvider>();
            var result = await authService.RequestAccessToken();
            if (!result.TryGetToken(out var token))
            {
                Navigation.NavigateToLogin("authentication/login-callback");
            }
        }
    }
}

2. Azure AD应用关键配置

  • 确保Blazor客户端与Web API应用处于同一Azure AD租户,且已配置API权限(添加Web API的访问范围并完成管理员授权)。
  • 在客户端应用的「身份验证」设置中,添加与代码中一致的重定向URI(如https://localhost:5001/authentication/login-callback),并勾选「ID令牌」和「访问令牌」选项。
  • 启用会话令牌:在客户端应用的「令牌配置」中,开启会话令牌功能,设置合理的会话超时与持久会话参数,让浏览器保留登录状态。

3. Web API端SSO支持

确保API端正确验证租户令牌,配置appsettings.json与服务:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "{你的租户ID}",
    "ClientId": "{你的API应用ID}",
    "Audience": "api://{你的API应用ID}"
}

常见问题排查

  • 检查浏览器第三方Cookie权限:Azure AD SSO依赖会话Cookie,若浏览器禁用第三方Cookie,需引导用户启用。
  • 确认重定向URI完全匹配:Azure AD配置的URI需与代码中一致,包括HTTP/HTTPS协议、端口号。
  • 验证用户会话状态:SSO自动登录的前提是用户当前浏览器已有有效的Azure AD登录会话,首次登录仍需手动输入凭证,后续会自动完成登录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:30:57