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

为现有Blazor WebAssembly应用配置Azure Active Directory认证

Blazor WebAssembly 集成Azure Active Directory认证补充步骤

你已经完成了基础NuGet包安装、服务器端配置和appsettings设置,还需要以下几步才能触发微软登录界面:

1. 客户端Program.cs配置

Blazor WASM是客户端应用,必须在客户端的Program.cs中添加认证服务配置(注意和服务器端区分开):

builder.Services.AddMsalAuthentication(options =>
{
    builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
    options.ProviderOptions.LoginMode = "redirect"; // 也可选择"popup"弹窗模式
});

2. 添加登录/登出UI组件

在页面布局(比如MainLayout.razor)中添加登录状态控件,用来触发登录操作:

<AuthorizeView>
    <Authorized>
        <p>欢迎, @context.User.Identity.Name!</p>
        <button @onclick="() => NavigationManager.NavigateTo("authentication/logout")">登出</button>
    </Authorized>
    <NotAuthorized>
        <button @onclick="() => NavigationManager.NavigateTo("authentication/login")">登录</button>
    </NotAuthorized>
</AuthorizeView>

@inject NavigationManager NavigationManager

3. 配置路由保护(可选但推荐)

如果要强制某些页面必须登录才能访问,在App.razor中用AuthorizeRouteView包裹路由组件:

<Router AppAssembly="@typeof(App).Assembly">
    <Found Context="routeData">
        <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
            <NotAuthorized>
                @if (!context.User.Identity.IsAuthenticated)
                {
                    <RedirectToLogin />
                }
                else
                {
                    <p>你没有权限访问此页面。</p>
                }
            </NotAuthorized>
        </AuthorizeRouteView>
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="@typeof(MainLayout)">
            <p role="alert">抱歉,未找到该页面。</p>
        </LayoutView>
    </NotFound>
</Router>

同时创建RedirectToLogin.razor组件:

@inject NavigationManager NavigationManager
@code {
    protected override void OnInitialized()
    {
        NavigationManager.NavigateTo($"authentication/login?returnUrl={Uri.EscapeDataString(NavigationManager.Uri)}");
    }
}

4. 验证Azure AD应用注册配置

确保Azure AD应用注册中:

  • 重定向URI设置正确,格式应为https://<你的应用域名>/authentication/login-callback(本地调试通常是https://localhost:xxxx/authentication/login-callback,需和appsettings里的CallbackPath完全对应)
  • 应用注册类型选择单页应用(SPA),因为Blazor WASM属于SPA范畴
  • 已授予基础API权限(比如User.Read)

5. 客户端appsettings.json同步配置

客户端wwwroot/appsettings.json也需要包含相同的AzureAd配置(服务器端配置是给API用的,客户端自身需要独立配置):

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "your-domain.onmicrosoft.com",
    "TenantId": "your-tenant-id",
    "ClientId": "your-client-id",
    "CallbackPath": "/authentication/login-callback"
  }
}

完成以上步骤后,运行应用点击登录按钮,就会跳转至微软登录界面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 08:01:01