Identityserver4 未在 Blazor 客户端中获得授权 api

Identityserver4 not authorized api in blazor client

我将身份服务器 4 与 Blazor 服务器端客户端一起使用

一切正常但令牌未授权api方法但令牌在服务器授权控制器中工作

授权类型或代码流程有问题吗?

服务器配置 class :

 public static class Configurations
    {
        public static IEnumerable<IdentityResource> GetIdentityResources() =>
            new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
            };

        public static IEnumerable<ApiResource> GetApis() =>
            new List<ApiResource> {
                new ApiResource("api1")
            };

        public static IEnumerable<ApiScope> GetApiScopes()
        {
            return new List<ApiScope>
            {
                // backward compat
                new ApiScope("api1")
            };
        }

        public static IEnumerable<Client> GetClients() => new List<Client>
        {
        new Client
            {
                ClientId = "client",
                AllowedGrantTypes = GrantTypes.Code,
                ClientSecrets =
                {
                    new Secret("secret".Sha256())
                },
                AllowedScopes = { 
                        "api1" ,
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                },
                RedirectUris = { "https://localhost:44372/signin-oidc" },

                AlwaysIncludeUserClaimsInIdToken = true,

                AllowOfflineAccess = true,
                RequireConsent = false,
                RequirePkce = true,
            }
        };

     
    }

服务器启动 class :

  public void ConfigureServices(IServiceCollection services)
        {

            services.AddDbContext<AppDbContext>(config =>
            {
                config.UseInMemoryDatabase("Memory");
            });

            // AddIdentity registers the services
            services.AddIdentity<IdentityUser, IdentityRole>(config =>
            {
                config.Password.RequiredLength = 4;
                config.Password.RequireDigit = false;
                config.Password.RequireNonAlphanumeric = false;
                config.Password.RequireUppercase = false;
            })
                .AddEntityFrameworkStores<AppDbContext>()
                .AddDefaultTokenProviders();

            services.ConfigureApplicationCookie(config =>
            {
                config.Cookie.Name = "IdentityServer.Cookie";
                config.LoginPath = "/Auth/Login";
                config.LogoutPath = "/Auth/Logout";
            });



            services.AddIdentityServer()
                .AddAspNetIdentity<IdentityUser>()
               //.AddInMemoryApiResources(Configurations.GetApis())
               .AddInMemoryIdentityResources(Configurations.GetIdentityResources())
               .AddInMemoryApiScopes(Configurations.GetApiScopes())
               .AddInMemoryClients(Configurations.GetClients())
               .AddDeveloperSigningCredential();

            services.AddControllersWithViews();
        }

api 启动 class :

            services.AddAuthentication("Bearer").AddIdentityServerAuthentication(option =>
            {
                option.Authority = "https://localhost:44313";
                option.RequireHttpsMetadata = false;
                option.ApiName = "api1";
            });

blazor 服务器端启动 class:

services.AddAuthentication(config =>
            {
                config.DefaultScheme = "Cookie";
                config.DefaultChallengeScheme = "oidc";
            })
                .AddCookie("Cookie")
                .AddOpenIdConnect("oidc", config =>
                {
                    config.Authority = "https://localhost:44313/";
                    config.ClientId = "client";
                    config.ClientSecret = "secret";
                    config.SaveTokens = true;
                    config.ResponseType = "code";
                    config.SignedOutCallbackPath = "/";
                    config.Scope.Add("openid");
                    config.Scope.Add("api1");
                    config.Scope.Add("offline_access");
                });

            services.AddMvcCore(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser() // site-wide auth
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });

我实际上没有在 API 中使用过 AddIdentityServerAuthentication 但你能试试下面的代码吗?从技术上讲是一样的,但也许这会奏效。

将您的 api 身份验证从 AddIdentityServerAuthentication 更改为 AddJwtBearer:

   services.AddAuthentication("Bearer").AddIdentityServerAuthentication(option =>
            {
                option.Authority = "https://localhost:44313";
                option.RequireHttpsMetadata = false;
                option.ApiName = "api1";
            });

   services.AddAuthentication("Bearer")
           .AddJwtBearer("Bearer", option =>
           {
               option.Authority = "https://localhost:44313";
               option.Audience = "api1";
               option.SaveToken = true;
           });

要解决此问题,您有 2 个选择:

1-(推荐)将范围添加到 API 资源,如下所示:

public static IEnumerable<ApiResource> GetApis() =>
            new List<ApiResource> {
                new ApiResource("api1")
                {
                    Scopes = new []{ "api1" }
                }
            };

        public static IEnumerable<ApiScope> GetApiScopes()
        {
            return new List<ApiScope>
            {
                // backward compat
                new ApiScope("api1")
            };
        }

2- 在 API 上更改您的代码以设置 ValidateAudience = false,如下所示:

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

这是我关于将 IdentityServer4 迁移到 v4 的博客https://nahidfa.com/posts/migrating-identityserver4-to-v4/