当我使用IdentityServer4时,出现了“需要代码挑战”的问题。

38

我正试图重定向到IdentityServer进行授权,但在重定向URL中出现了“需要代码挑战”的错误信息。

错误消息显示invalid_request并要求代码挑战,同时显示我的重定向URL为http://localhost:44367/signin-oidc#error=invalid_request&error_description=code%20challenge%20required&state=CfDJ8Cq6lLUEMhZLqMhFVN

这是我的客户端配置:

namespace TestClient
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddControllersWithViews();

            ConfigureIdentityServer(services);
            services.AddCors();
        }

        private void ConfigureIdentityServer(IServiceCollection services)
        {
            var builder = services.AddAuthentication(options => SetAuthenticationOptions(options));
            services.AddMvcCore()
                .AddAuthorization();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

            builder.AddCookie();
            builder.AddOpenIdConnect(options => SetOpenIdConnectOptions(options));
        }

        private void SetAuthenticationOptions(AuthenticationOptions options)
        {
            options.DefaultScheme = Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectDefaults.AuthenticationScheme;
        }

        private void SetOpenIdConnectOptions(OpenIdConnectOptions options)
        {
            options.Authority = "https://localhost:44346";
            options.ClientId = "TestIdentityServer";
            options.RequireHttpsMetadata = false;
            options.Scope.Add("profile");
            options.Scope.Add("openid");
            options.Scope.Add("TestIdentityServer");
            options.ResponseType = "code id_token";
            options.SaveTokens = true;
            options.ClientSecret = "0b4168e4-2832-48ea-8fc8-7e4686b3620b";
        }


        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.

            }
            app.UseHsts();
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseCors(builder => builder
                .AllowAnyOrigin()
                .AllowAnyHeader()
                .AllowAnyMethod()
            );

            app.UseCookiePolicy();
            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

以下是我的IdentityService4配置:

  public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IdentityModelEventSource.ShowPII = true;
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();
            services.AddControllersWithViews();
            services.AddRazorPages();

            services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_3_0);
            services.Configure<IISOptions>(iis =>
            {
                iis.AuthenticationDisplayName = "Windows";
                iis.AutomaticAuthentication = false;
            });

            var builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents = true;
                options.Events.RaiseSuccessEvents = true;
            });
            // this adds the config data from DB (clients, resources)

            builder.AddInMemoryIdentityResources(Configuration.GetSection("IdentityResources"));
            builder.AddInMemoryApiResources(Configuration.GetSection("ApiResources"));
            builder.AddInMemoryClients(Configuration.GetSection("clients"));

            services.AddAuthentication();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.

            }
            app.UseHsts();
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();
            app.UseIdentityServer();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
    }

以及 appsettings.json

"IdentityResources": [
    {
      "Name": "openid",
      "DisplayName": "Your user identifier",
      "Required": true,
      "UserClaims": [
        "sub"
      ]
    },
    {
      "Name": "profile",
      "DisplayName": "User profile",
      "Description": "Your user profile information (first name, last name, etc.)",
      "Emphasize": true,
      "UserClaims": [
        "name",
        "family_name",
        "given_name",
        "middle_name",
        "preferred_username",
        "profile",
        "picture",
        "website",
        "gender",
        "birthdate",
        "zoneinfo",
        "locale",
        "updated_at"
      ]
    }
  ],

  "ApiResources": [
    {
      "Name": "TestIdentityServer",
      "DisplayName": "TestIdentityServer API Services",
      "Scopes": [
        {
          "Name": "TestIdentityServer",
          "DisplayName": "TestIdentityServer API Services"
        }
      ]
    }
  ],

  "Clients": [
    {
      "ClientId": "TestIdentityServer",
      "ClientName": "TestIdentityServer Credentials Client",

      // 511536EF-F270-4058-80CA-1C89C192F69A
      "ClientSecrets": [ { "Value": "entAuCGhsOQWRYBVx26BCgZxeMt/TqeVZzzpNJ9Ub1M=" } ],
      "AllowedGrantTypes": [ "hybrid" ],
      "AllowedScopes": [ "openid", "profile", "TestIdentityServer" ],
      "RedirectUris": [ "http://localhost:44367/signin-oidc" ],
      //"FrontChannelLogoutUris": [ "http://localhost:44367/Home/Privacy" ],
      //"PostLogoutRedirectUris": [ "http://localhost:44367/Home/Privacy" ],
      "redirect_uri": "http://localhost:44367/signin-oidc"
    }

我遇到了同样的问题 - 你能解决吗? - Eric Patrick
我也遇到了同样的问题。我甚至不确定什么是code-challenge,因为常规的GrantType.Code并没有要求这个。 - Space Cadet
1
为客户端设置RequirePKCE=false。 - GPuri
5个回答

53

我相信您正在使用版本4.0或更高版本,如果我猜对了,请告诉我。

根据文档,4.0及以上版本默认使用code flow + PKCE,这比Hybrid flow更安全。

这里是链接 https://identityserver4.readthedocs.io/en/latest/topics/grant_types.html 和相关的github问题链接 https://github.com/IdentityServer/IdentityServer4/issues/3728,描述了它作为一个重大变化。

当我在其中一个项目中将IdentityServer4包升级到最新版本时,我也遇到了约2小时的问题。

如果您想使用Hybrid flow,请在客户端配置中将RequirePkce设置为false

"Clients": {
   /* Code removed for brevity */
      RequirePkce : "false"
    }

是的,在新版本的IS4中,我们需要确认在客户端和服务器配置中都不使用Pkce。 - Terai

17

今天遇到了这个错误,通过切换到以下内容解决了它:

options.ResponseType = "code id_token";

options.ResponseType = "code";
options.UsePkce = true;

以下是我的完整客户端选项:

options.Authority = "http://localhost:8000";
options.RequireHttpsMetadata = false; // dev only

options.ClientId = "testAPI";
options.ClientSecret = secret;

// code flow + PKCE (PKCE is turned on by default)
options.ResponseType = "code";
options.UsePkce = true;

options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("offline_access");
options.Scope.Add("testAPI");

options.ClaimActions.MapJsonKey("website", "website");

//options.ResponseMode = "form_post";
//options.CallbackPath = "/signin-oidc";

// keeps id_token smaller
options.GetClaimsFromUserInfoEndpoint = true;
options.SaveTokens = true;

另外,由于我在docker上使用IdentityServer并在主机上测试客户端,因此我不得不配置额外的重定向Uri以进行测试:

RedirectUris =
{
    "http://localhost:5001/signin-oidc",
    "http://host.docker.internal:5001/signin-oidc",
    "http://notused"
},

我的实现基于Dominic Baier在GitHub上的样例。

编辑:我现在明白了,对于我的情况,响应类型只能是“code”,因为我的客户端配置是Authorization Code + PKCE(OAuth2流程)。您配置为“Hybrid”(OIDC流程),支持“code id_token”,因此尽管我们收到了相同的错误消息,但问题是不同的。


1

2
欢迎来到Stack Overflow。您能否解释一下链接中的内容?即使链接过期,您的答案也必须保持有效。 - LuizZ
PKCE对于安全至关重要。我建议您重新启用它,除非您有非常具体的禁用原因并且了解您的威胁模型。 - Stuart Frankish

1

解决此问题的步骤:

1- 在IdentityServer配置中的new Client()中设置RequirePkce=true

2- 在.AddOpenIdConnect()中设置options.UsePkce = true;

3- 并在同一位置添加以下内容:

 options.Events = new OpenIdConnectEvents
               {
                   OnRedirectToIdentityProvider = context =>
                   {
                       // Generate the code_verifier value
                       var codeVerifier = GenerateCodeVerifier();

                       // Store the code_verifier in a secure location (e.g. session)
                       context.Properties.Items.Add("code_verifier", codeVerifier);

                       // Hash the code_verifier to create the code_challenge value
                       var codeChallenge = GenerateCodeChallenge(codeVerifier);

                       // Add the code_challenge parameter to the authorization request
                       context.ProtocolMessage.SetParameter("code_challenge", codeChallenge);
                       context.ProtocolMessage.SetParameter("code_challenge_method", "S256");

                       return Task.CompletedTask;
                   }
               };

这里是在这个配置中使用的两种方法:

 private static string GenerateCodeVerifier()
    {
        using (var rng = RandomNumberGenerator.Create())
        {
            var bytes = new byte[32];
            rng.GetBytes(bytes);
            return Base64Url.Encode(bytes);
        }
    }

    private static string GenerateCodeChallenge(string codeVerifier)
    {
        using (var sha256 = SHA256.Create())
        {
            var challengeBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(codeVerifier));
            return Base64Url.Encode(challengeBytes);
        }
    }

0
运行您的应用程序,并在重定向到浏览器页面后,删除所有的cookies。站点设置->使用情况->Cookies->清除与该URL(https://localhost:5002)相对应的数据,然后重新启动应用程序。这样就解决了代码挑战问题。
        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
         .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
         .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
         {
             options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
             options.Authority = "https://localhost:5005";
             options.ClientId = "movies_mvc_client";
             options.ClientSecret = "secret";
             options.ResponseType = "code";

             options.SaveTokens = true;
            // options.RequireHttpsMetadata = false;
             options.GetClaimsFromUserInfoEndpoint = true;
             options.Scope.Add("openid");
             options.Scope.Add("profile");
         });

Config.cs - 身份认证服务器

                new Client
            {
             ClientId = "movies_mvc_client",
            ClientSecrets = { new Secret("secret".Sha256()) },
                
            AllowedGrantTypes = GrantTypes.Code,

             RedirectUris = { "https://localhost:5002/signin-oidc" },
            //    FrontChannelLogoutUri = "https://localhost:44300/signout-oidc",
             PostLogoutRedirectUris = { "https://localhost:5002/signout-callback-oidc" },

             AllowOfflineAccess = true,
             AllowedScopes = { "openid", "profile","movies_mvc_client"}
            }

这个方法是如何解决问题的(为什么它有效)? - ryanwebjackson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接