Search code examples
migrationidentityserver4

Migrating IdentityServer4 from v3 to v4


How to fix run time errors on MVC app and API, after migrating a working IdentityServer4 solution from v3 to v4?

IdentityServer4 setup:

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 client config:

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 app OpenId Connect setup:

.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;
   });

Error after migration:

Sorry, there was an error : invalid_scope
Invalid scope

API setup:

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

API error after migration:

401 Unauthorized

Solution

  • The short answer is to follow 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.

    And I have it blogged https://nahidfa.com/posts/migrating-identityserver4-to-v4/ to go through the changes with reasoning behind it.