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

ASP.NET Core中如何自定义OpenIdConnect中间件的Token端点?

自定义OpenIdConnect中间件的Token端点方法

当然可以自定义Token端点,使用Microsoft.AspNetCore.Authentication.OpenIdConnect中间件时有两种常用实现方式:

  • 直接指定TokenEndpoint属性
    如果身份提供商的OpenID Connect发现文档不存在,或者你需要强制覆盖默认的Token端点,只需在配置OpenIdConnect选项时显式设置TokenEndpoint字段即可。示例代码如下:

    services.AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie()
    .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
    {
        options.Authority = "你的身份提供商基础地址";
        options.ClientId = "你的客户端ID";
        options.ClientSecret = "你的客户端密钥";
        // 替换为自定义的Token端点路径
        options.TokenEndpoint = "/profile/oidc/token";
        options.ResponseType = "code";
        options.SaveTokens = true;
        // 根据需要添加其他配置,比如Scopes等
    });
    
  • 禁用自动发现,手动配置所有端点
    如果身份提供商没有提供标准的发现文档,或者发现文档中的端点信息不正确,你可以禁用自动发现功能,手动配置所有必需的端点。示例代码:

    services.AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie()
    .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
    {
        options.Authority = "你的身份提供商基础地址";
        options.ClientId = "你的客户端ID";
        options.ClientSecret = "你的客户端密钥";
        // 禁用自动发现
        options.MetadataAddress = null;
        options.RequireHttpsMetadata = false; // 生产环境建议设为true,确保HTTPS传输
        // 手动配置所有必要的端点
        options.AuthorizationEndpoint = "/profile/oidc/authorize";
        options.TokenEndpoint = "/profile/oidc/token";
        options.UserInformationEndpoint = "/profile/oidc/userinfo";
        options.ResponseType = "code";
        options.SaveTokens = true;
    });
    

注意:如果身份提供商的授权端点、用户信息端点等也不是标准路径,需要同步手动配置对应的属性。另外,确保客户端ID、密钥、响应类型等核心配置与身份提供商的要求一致,避免因其他配置错误导致的授权失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 23:09:55