skoruba / Duende.IdentityServer.Admin

The administration for the Duende IdentityServer and Asp.Net Core Identity ⚡
Apache License 2.0
542 stars 188 forks source link

Tokens have roles, but claims do not. #210

Closed yunlang closed 3 months ago

yunlang commented 3 months ago

Question

hi, skoruba, I'm working hard to learn from the great work you've done. Today, i'd like to ask you about an issue I've been stuck on.

  1. Here is the parsing of the token received after login. (HS256) image

  2. As you can see, the role exists inside the obtained token. (Admin)

  3. But it doesn't exist inside a claims. image

  4. As a result, the paragraph that validates the role keeps saying I don't have permission. image

  5. I can't figure out which part to look at. Please help

Code

  services.AddAuthentication(options =>
  {
      options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
      options.DefaultChallengeScheme = "oidc";
  })
  .AddCookie(options =>
  {
      options.Cookie.Name = siteConfiguration.CookieName;
  })
  .AddOpenIdConnect("oidc", options =>
  {
      options.Authority = siteConfiguration.IdentityServerBaseUrl;
      options.RequireHttpsMetadata = false;
      options.ClientId = siteConfiguration.ClientId;
      options.ClientSecret = siteConfiguration.ClientSecret;
      options.ResponseType = siteConfiguration.OidcResponseType;
      options.UsePkce = true;

      options.Scope.Clear();
      foreach (string scope in siteConfiguration.Scopes)
      {
          options.Scope.Add(scope);
      }
      options.GetClaimsFromUserInfoEndpoint = true;
      options.SaveTokens = true;

      options.TokenValidationParameters = new TokenValidationParameters
      {
          NameClaimType = siteConfiguration.TokenValidationClaimName,
          RoleClaimType = siteConfiguration.TokenValidationClaimRole
      };
  });

  services.AddAuthorization(options =>
  {
      options.AddPolicy(AuthorizationConsts.AdministrationPolicy, policy => policy.RequireRole(RoleTypes.Admin));

      options.AddPolicy(AuthorizationConsts.ManagerPolicy,
          policy => policy.RequireRole(
              RoleTypes.Admin,
              RoleTypes.Manager
          ));

      options.AddPolicy(AuthorizationConsts.LocalManagerPolicy,
          policy => policy.RequireRole(
              RoleTypes.Admin,
              RoleTypes.Manager,
              RoleTypes.LocalManager
          ));

      options.AddPolicy(AuthorizationConsts.UserPolicy,
          policy => policy.RequireRole(
              RoleTypes.Admin,
              RoleTypes.Manager,
              RoleTypes.LocalManager,
              RoleTypes.User
          ));
  });