首页 > 解决方案 > 如何使用 ocelot 指定控制器方法角色?

问题描述

我有一个发布 JWT 的授权服务器。在 Ocelot 网关上还运行着微服务,我需要仅为管理器访问服务控制器方法。在微服务的控制器方法上设置属性 [Authorize(Roles="Manager") 时,会发生错误,如果删除该属性,一切正常,但没有所需角色的区分。如何按角色区分?

System.InvalidOperationException:未指定 authenticationScheme,也未找到 DefaultChallengeScheme。可以使用 AddAuthentication(string defaultScheme) 或 AddAuthentication(Action configureOptions) 设置默认方案。在 Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, String scheme, AuthenticationProperties properties) 在 Microsoft.AspNetCore 的 Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)。 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext 上下文)的 Authorization.AuthorizationMiddleware.Invoke(HttpContext 上下文)

HEADERS Connection: keep-alive Content-Type: application/json Accept: / Accept-Encoding: gzip, deflate, br Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InNpbXBsZVVzZXIiLCJzdWIiOiIwIiwicm9sZSI6IlVzZXIiLCJleHAiOjE2MTg1NTc3OTgsImlzcyI6ImF1dGhTZXJ2ZXIiLCJhdWQiOiJyZXNvdXJjZVNlcnZlciJ9.91b5WT-Uww5sJoYZ0y8Dyv8KAbo63oRZBaiZjLlY1BQ Host: localhost:7002 User-Agent: PostmanRuntime/7.26.10 traceparent :00-cb7ffff4bf57a947a0b0dd7e0edc0fcb-bddaced012f7084a-00 内容长度:0 邮递员令牌:194aeaa6-56bb-44fd-8879-7d211618787d

豹猫


{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/Survey/all-surveys/{userId}",
      "DownstreamScheme": "https",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 7002
        }
      ],
      "UpstreamPathTemplate": "/api/surveys/{userId}",
      "UpstreamHttpMethod": [ "GET" ],
      "AuthenticationOptions": {
        "AuthenticationProviderKey": "Bearer",
        "AllowedScopes": [],
        "RouteClaimsRequirement": {
          "UserType": "Manager"
        }
      }
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "https://localhost:7000"
  }
}

网关启动.cs

 public void ConfigureServices(IServiceCollection services)
        {
            var authOptions = this.Configuration.GetSection("Auth").Get<AuthOptions>();
            services.AddAuthentication(option =>
            {
                option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }
                )
                .AddJwtBearer(options =>
                {
                    options.RequireHttpsMetadata = true;
                    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidIssuer = authOptions.Issuer,
                        ValidateAudience = true,
                        ValidAudience = authOptions.Audience,
                        ValidateLifetime = true,
                        IssuerSigningKey = authOptions.GetSymmetricSecurityKey(), //hsa256
                        ValidateIssuerSigningKey = true
                    };
                });
            services.AddControllers();
            services.AddOcelot(Configuration);
        }
        public async void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            await app.UseOcelot();
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

startup.cs 调查服务

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

标签: asp.net-core-webapiasp.net-core-5.0

解决方案


推荐阅读