将 IdentityServer4 从 v3 迁移到 v4

Migrating IdentityServer4 from v3 to v4

如何在将有效的 IdentityServer4 解决方案从 v3 迁移到 v4 后修复 MVC 应用和 API 上的 运行 时间错误?

IdentityServer4 设置:

var builder = services.AddIdentityServer(    
   .AddInMemoryIdentityResources(Config.Ids)
   .AddInMemoryApiResources(Config.Apis)
   .AddInMemoryClients(Config.Clients)
   .AddTestUsers(TestUsers.Users);

public static IEnumerable<ApiResource> Apis =>
   new ApiResource[] 
   {
      new ApiResource("api1"),
      new ApiResource("api2")
   };

MVC 客户端配置:

new Client
   {
      ClientName = "MVC website",
      ClientId = "mvcclient",
      ClientSecrets =
      {
         new Secret("secret2".Sha256())
      },
      AllowedGrantTypes = GrantTypes.Code,
      RequireConsent = false,
      RequirePkce = true,

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

      AllowedScopes = {"openid", "profile", "offline_access", "api1", "api2" },

      AllowOfflineAccess = true,
   },

MVC 应用 OpenId Connect 设置:

.AddOpenIdConnect("oidc", options =>
   {
      options.Authority = "http://localhost:5000";
      options.RequireHttpsMetadata = false;
      options.ClientId = "mvcclient";
      options.ClientSecret = "secret2";
      options.ResponseType = "code";
      options.SaveTokens = true;
      options.Scope.Add("api1");
      options.Scope.Add("api2");
      options.Scope.Add("offline_access");
      options.GetClaimsFromUserInfoEndpoint = true;
   });

迁移后出错:

Sorry, there was an error : invalid_scope
Invalid scope

API 设置:

services.AddAuthentication("Bearer").AddJwtBearer("Bearer",
   options =>
   {
      options.Authority = "http://localhost:5000";
      options.Audience = "api1";
      options.RequireHttpsMetadata = false;
   });

API 迁移后错误:

401 Unauthorized

简答如下migration-steps-to-v4

As described above, starting with v4, scopes have their own definition and can optionally be referenced by resources. Before v4, scopes where always contained within a resource.

To migrate to v4 you need to split up scope and resource registration, typically by first registering all your scopes (e.g. using the AddInMemoryApiScopes method), and then register the API resources (if any) afterwards. The API resources will then reference the prior registered scopes by name.

我已将它写在博客 https://nahidfa.com/posts/migrating-identityserver4-to-v4/ 中,以了解这些变化背后的原因。