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

使用Identity Server 4获取授权码时提示‘Sorry, there was an error’求助

IdentityServer4授权码流程(Authorization Code Flow)报错排查方案

尝试使用IdentityServer4实现Authorization Code Flow时,生成授权码阶段始终显示通用错误页面(标题Error,内容'Sorry, there was an error'),Postman和代码提交GET请求均触发该错误。测试流程为:启动IdentityServer、API服务器及MVC站点(确保回调URL可用),在Postman中点击「Get New Access Token」仍报错。


现有配置信息

客户端配置

new Client
{
    ClientId = "mvc",
    ClientSecrets = { new Secret("secret".Sha256()) },

    AllowedGrantTypes = GrantTypes.Code,

    // 登录后重定向地址
    RedirectUris = { "https://localhost:5002/signin-oidc" },

    // 登出后重定向地址
    PostLogoutRedirectUris = { "https://localhost:5002/signout-callback-oidc" },

    AllowOfflineAccess = true,
    AllowAccessTokensViaBrowser = true,

    AllowedScopes = new List<string>
    {
        IdentityServerConstants.StandardScopes.OpenId,
        IdentityServerConstants.StandardScopes.Profile,
        "api1",
        IdentityServerConstants.StandardScopes.Email
    }
}

测试用户配置

new TestUser
{
    SubjectId = "88421113",
    Username = "bob",
    Password = "bob",
    Claims =
    {
        new Claim(JwtClaimTypes.Name, "Bob Smith"),
        new Claim(JwtClaimTypes.GivenName, "Bob"),
        new Claim(JwtClaimTypes.FamilyName, "Smith"),
        new Claim(JwtClaimTypes.Email, "BobSmith@email.com"),
        new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
        new Claim(JwtClaimTypes.WebSite, "http://bob.com"),
        new Claim(JwtClaimTypes.Address, JsonSerializer.Serialize(address), IdentityServerConstants.ClaimValueTypes.Json)
    }
}

Startup配置

public class Startup
{
    public IWebHostEnvironment Environment { get; }

    public Startup(IWebHostEnvironment environment)
    {
        Environment = environment;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        // 启用MVC视图控制器
        services.AddControllersWithViews();

        services.AddAuthentication()
            .AddGoogle("Google", options =>
            {
                options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

                options.ClientId = "<insert here>";
                options.ClientSecret = "<insert here>";
            });

        services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication (options =>
            {
                options.Authority = "https://localhost:5001";
                options.ApiName = "testapis";
            });


        var builder = services.AddIdentityServer(options =>
        {
            options.EmitStaticAudienceClaim = true;
        })
        .AddDeveloperSigningCredential()        // 仅开发环境使用,生产需替换为正式证书
        .AddInMemoryIdentityResources(Config.IdentityResources)
        .AddInMemoryApiScopes(Config.ApiScopes)
        .AddInMemoryClients(Config.Clients)
        .AddTestUsers(TestUsers.Users)
        .AddCustomTokenRequestValidator<CustomTokenRequestValidator>();

        // 重复添加了开发签名凭证,需移除其中一个
        builder.AddDeveloperSigningCredential();
    }

    public void Configure(IApplicationBuilder app)
    {
        if (Environment.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        
        app.UseIdentityServer();
        app.UseAuthentication();

        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
        });
    }
}

Postman配置截图

Postman测试配置


核心排查与修复步骤

1. 移除重复的签名凭证配置

Startup中重复调用了.AddDeveloperSigningCredential(),这会导致签名密钥冲突,直接引发认证流程错误。删除其中一行即可:

// 移除下面这行重复代码
// builder.AddDeveloperSigningCredential();

2. 匹配Postman回调地址与客户端配置

从截图看,Postman的Callback URL是https://oauth.pstmn.io/v1/callback,但客户端配置的RedirectUris仅包含https://localhost:5002/signin-oidc。授权码流程要求回调地址必须在客户端允许列表内,二选一调整:

  • 方案一:修改客户端配置,添加Postman回调地址:
    RedirectUris = { 
        "https://localhost:5002/signin-oidc",
        "https://oauth.pstmn.io/v1/callback" // 新增Postman回调
    },
    
  • 方案二:在Postman中把Callback URL改为https://localhost:5002/signin-oidc

3. 验证API Scope一致性

客户端配置中AllowedScopes包含"api1",但Startup中API认证配置的ApiName是"testapis",需确保Config.ApiScopes中存在"api1"的定义:

// 确保Config.ApiScopes中有如下配置
new ApiScope("api1", "API 1 Access")

4. 启用详细日志定位根因

开发环境下开启IdentityServer调试日志,直接查看具体错误原因。修改appsettings.json添加日志配置:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information",
      "IdentityServer4": "Debug" // 开启IdentityServer调试日志
    }
  }
}

运行后查看Visual Studio输出窗口,即可获取参数错误、Scope不存在等具体报错信息。

5. 校验Postman参数完整性

确保Postman中:

  • Auth URL为IdentityServer授权端点:https://localhost:5001/connect/authorize
  • Access Token URL为令牌端点:https://localhost:5001/connect/token
  • Client ID为mvc,Client Secret为secret(注意选择正确的认证方式,如Basic Auth)
  • Scope包含openid profile api1 email,与客户端配置的AllowedScopes完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:57:10