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

Blazor Server集成Azure AD:实现登出后跳转至登录页

解决Blazor Server + Azure AD登出后自动跳转登录页的方案

1. 修改项目登出逻辑配置

在项目的Program.cs中,配置OpenID Connect事件,指定登出后的跳转目标为登录页:

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
    .EnableTokenAcquisitionToCallDownstreamApi()
    .AddInMemoryTokenCaches();

// 配置登出回调地址
builder.Services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    options.Events.OnRedirectToIdentityProviderForSignOut = async context =>
    {
        // 替换为你的登录页路径,比如根路径"/"或专门的"/login"
        context.PostLogoutRedirectUri = "/login";
        await Task.CompletedTask;
    };
});

2. 调整Azure AD应用的注销URL配置

在Azure门户的AD应用注册页面,进入认证板块:

  • 找到前端/移动区域的注销URL
  • 填写应用登录页的完整URL(例如本地开发用https://localhost:5001/login,生产环境用https://your-app-domain/login)
  • 确保该URL已被添加到应用的已注册重定向URI或注销URL列表中,避免被Azure AD拦截

3. 确保登录页允许匿名访问

如果登录页是Razor页面(如Pages/Login.cshtml),添加匿名访问特性并完善登录触发逻辑:

[AllowAnonymous]
public class LoginModel : PageModel
{
    public async Task OnGet(string returnUrl = "/")
    {
        await HttpContext.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties
        {
            RedirectUri = returnUrl
        });
    }
}

如果是Blazor组件作为登录页,在组件顶部添加:

@attribute [AllowAnonymous]

4. 优化登出按钮的触发逻辑

在Blazor组件的登出按钮中,明确指定登出后的跳转目标:

<button @onclick="HandleLogout">登出</button>

@code {
    [Inject]
    private NavigationManager NavManager { get; set; }

    [Inject]
    private SignOutSessionStateManager SignOutManager { get; set; }

    private async Task HandleLogout()
    {
        await SignOutManager.SetSignOutState();
        // 跳转到AD登出端点并指定回调到登录页
        var encodedRedirectUri = Uri.EscapeDataString("/login");
        NavManager.NavigateTo($"/MicrosoftIdentity/Account/SignOut?post_logout_redirect_uri={encodedRedirectUri}", forceLoad: true);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 16:22:55