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

如何在Azure MVC应用中通过OIDC正确实现登出功能?

解决Azure AD MVC应用内Action实现登出并跳转的问题

1. 修正登出Action的代码逻辑

你之前的代码未正确触发OpenID Connect的完整登出流程,改用SignOutResult统一处理,同时可插入自定义逻辑:

public async Task<IActionResult> Logout()
{
    // 在这里添加自定义逻辑,比如记录登出日志、清理用户关联数据等
    // 示例:_activityLogger.LogUserLogout(User.Identity.Name);

    // 先清理本地Cookie认证会话
    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    
    // 触发OpenID Connect登出流程,完成后跳转至首页
    return SignOut(
        new AuthenticationProperties { RedirectUri = "/" },
        OpenIdConnectDefaults.AuthenticationScheme
    );
}

2. 确认Azure AD应用注册的配置

要让跳转生效,必须在Azure门户的应用注册中配置允许的回调URL:

  • 进入你的Azure AD应用注册页面,打开认证选项卡
  • 在Web平台的重定向URI列表中,确保https://localhost:1234/signout-oidc已添加
  • 在登出URL字段中填入目标跳转地址(比如https://localhost:1234/),并确保该地址也在已批准的重定向URI列表内

3. 检查项目的认证中间件配置

在Program.cs(或Startup.cs)中,确保OpenID Connect配置包含登出回调路径和跳转处理逻辑:

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
    options.ClientId = "你的Azure AD客户端ID";
    options.ClientSecret = "你的Azure AD客户端密钥";
    options.Authority = "https://login.microsoftonline.com/你的租户ID/v2.0";
    options.ResponseType = "code";
    options.Scope.Add("openid");
    options.Scope.Add("profile");
    
    // 指定登出回调路径,与Azure AD配置一致
    options.SignedOutCallbackPath = "/signout-oidc";
    
    // 处理登出完成后的跳转
    options.Events = new OpenIdConnectEvents
    {
        OnSignedOutCallbackRedirect = context =>
        {
            context.Response.Redirect(context.Properties.RedirectUri);
            context.HandleResponse();
            return Task.CompletedTask;
        }
    };
});

4. 避免直接访问/signout-oidc

默认的/signout-oidc端点由中间件处理,无对应视图,因此会显示空白页。让用户点击登出按钮时直接调用你编写的Logout Action,即可全程在应用内完成登出并跳转,无需接触该空白端点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:10:35