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

如何在OpenIddict的登出端点获取ClientId?

让登出请求携带ClientId的配置方法

要让OpenIdConnect客户端发起的登出请求带上client_id参数,只需在客户端的OpenIdConnect配置中添加事件处理,手动注入该参数即可,具体步骤如下:

客户端配置修改

在客户端的身份认证配置(通常在Program.cs或Startup.cs中),针对AddOpenIdConnect添加OnRedirectToIdentityProviderForSignOut事件处理,将客户端ID注入到登出请求的协议消息中:

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    // 基础配置(根据你的实际环境调整)
    options.Authority = "你的OpenIddict服务器地址";
    options.ClientId = "你的客户端ID";
    options.ClientSecret = "你的客户端密钥";
    options.ResponseType = "code";
    options.SaveTokens = true;

    // 配置登出时携带client_id
    options.Events = new OpenIdConnectEvents
    {
        OnRedirectToIdentityProviderForSignOut = context =>
        {
            // 将客户端ID添加到登出请求参数中
            context.ProtocolMessage.ClientId = options.ClientId;
            return Task.CompletedTask;
        }
    };
});

你的原有LogOut接口代码无需修改,保持原样即可:

[Route("/logout")]
[HttpGet]
public IActionResult LogOut()
{
    return SignOut(new AuthenticationProperties
    {
        RedirectUri = "/status"
    }, CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme);
}

服务器端验证

配置完成后,当客户端发起登出请求时,client_id参数会被自动携带到OpenIddict服务器。此时你可以直接通过HttpContext.GetOpenIddictServerRequest().ClientId获取到有效的客户端ID,进而查询客户端显示名称等信息。

如果未配置client_id,也可以通过请求中的id_token_hint解析获取客户端信息,示例代码如下:

var request = HttpContext.GetOpenIddictServerRequest();
if (!string.IsNullOrEmpty(request.IdTokenHint))
{
    var principal = await HttpContext.ValidateIdTokenHintAsync();
    if (principal != null)
    {
        string clientId = principal.FindFirst(OpenIddictConstants.Claims.ClientId)?.Value;
        // 根据clientId查询客户端显示名称等信息
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:27:25