将IdentityServer4从v3迁移到v4

时间:2020-07-03 20:35:24

标签: migration identityserver4

在将有效的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

1 个答案:

答案 0 :(得分:0)

简短的答案是遵循migration-steps-to-v4

如上所述,从v4开始,作用域具有自己的定义,并且可以选择由资源引用。在v4之前,范围始终包含在资源中。

要迁移到v4,您需要拆分作用域和资源注册,通常需要先注册所有作用域(例如,使用AddInMemoryApiScopes方法),然后再注册API资源(如果有)。然后,API资源将按名称引用先前注册的范围。

我把它写在https://nahidfa.com/posts/migrating-identityserver4-to-v4/上以通过推理进行更改。