You need to enable JavaScript to run this app. ASP.NET Core 3.1 微服务架构下Ocelot集成JWT登录返回401未授权排查
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 3.1 微服务架构下Ocelot集成JWT登录返回401未授权排查

基于ASP.NET Core 3.1微服务架构下登录请求经Ocelot网关返回401问题排查

当前项目基于ASP.NET Core 3.1 API搭建微服务架构,已集成JWT、Ocelot、认证服务相关依赖,调用登录接口时直接返回401未授权错误,登录请求无法进入Auth服务的LoginAction方法。以下为各环节已配置的代码与问题定位:

当前各环节配置详情

1. Ocelot路由配置(ocelot.json)

在路由规则中添加了AuthenticationOptions配置项,具体内容:

"Routes": [
    {
      "DownstreamPathTemplate": "/api/auth/{path}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 52150
        }
      ],
      "UpstreamPathTemplate": "/identity/{path}",
      "UpstreamHttpMethod": [
        "Get",
        "Post",
        "Put",
        "Delete"
      ],
      "AuthenticationOptions": {
        "AuthenticationProviderKey": "MY_SECRET_KEY",
        "AllowedScopes": []
      }
    }
  ]

2. API网关层Startup.cs配置

在网关层实现了JWT认证逻辑,具体代码:

public void ConfigureServices(IServiceCollection services)
        {
            var jwtConfig = Configuration.GetSection("JWT");
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig["Secret"]));
            string providerKey = "MY_SECRET_KEY";

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,
                ValidateIssuer = true,
                ValidIssuer = jwtConfig["Issuer"],
                ValidateAudience = true,
                ValidAudience = jwtConfig["Audience"],
                ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero,
                RequireExpirationTime = true,
            };

            services.AddAuthentication(config =>
            {
                config.DefaultAuthenticateScheme = providerKey;
            });

            services.AddAuthentication()
                    .AddJwtBearer(providerKey, config =>
                    {
                        config.RequireHttpsMetadata = false;
                        config.TokenValidationParameters = tokenValidationParameters;
                    });

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader());
            });

            services.AddOcelot(Configuration);
            //services.AddControllers();
        }

public async void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors("CorsPolicy");


            app.UseAuthentication();
            app.UseRouting();

            await app.UseOcelot();
            

            //app.UseEndpoints(endpoints =>
            //{
            //    //endpoints.MapControllers();
            //});
        }

3. Auth认证服务Startup.cs配置

独立认证服务中配置的JWT认证逻辑:

public void ConfigureServices(IServiceCollection services)
        {
            var jwtConfig = Configuration.GetSection("JWT");
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig["Secret"]));
            string providerKey = "MY_SECRET_KEY";

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,
                ValidateIssuer = true,
                ValidIssuer = jwtConfig["Issuer"],
                ValidateAudience = true,
                ValidAudience = jwtConfig["Audience"],
                ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero,
                RequireExpirationTime = true,
            };

            services.AddAuthentication(config =>
            {
                config.DefaultAuthenticateScheme = providerKey;
            });

            services.AddAuthentication()
                    .AddJwtBearer(providerKey, config =>
                    {
                        config.RequireHttpsMetadata = false;
                        config.TokenValidationParameters = tokenValidationParameters;
                    });

            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthentication();
            app.UseRouting();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

4. AuthController登录动作方法

目前登录请求无法进入该方法,代码如下:

[HttpPost("login")]
        
        public async Task<IActionResult> LoginAsync([FromForm] Login model)
        {
            var result = await authService.LoginAsync(model);

            if (result.Response.Success)
            {
                return Ok(result);
            }
            else
            {
                return BadRequest(result);
            }
        }

问题根因与对应修复方案

  • 登录路由被网关强制拦截认证
    当前ocelot.json的路由规则对所有匹配/identity/{path}的请求(含登录接口)统一配置了AuthenticationOptions,网关转发请求前会先校验请求是否携带有效JWT。但登录请求的核心作用是获取JWT,客户端发起登录时不可能携带已有的有效令牌,因此网关直接拦截返回401,请求根本无法到达下游Auth服务。
    修复:为登录接口单独配置路由规则,移除该规则下的AuthenticationOptions配置;或在网关认证逻辑中将登录路径加入匿名访问白名单。

  • 网关层JWT认证方案注册失败
    代码中连续两次调用AddAuthentication方法:第一次调用时设置了默认认证方案为MY_SECRET_KEY,但第二次无参数调用AddAuthentication()会直接覆盖之前的服务配置,导致Ocelot根据AuthenticationProviderKey查找对应认证方案时匹配失败。
    修复:合并两次AddAuthentication调用,在同一注册链路中完成默认方案设置与JWT Bearer配置的关联:

    services.AddAuthentication(config =>
    {
        config.DefaultAuthenticateScheme = providerKey;
        config.DefaultChallengeScheme = providerKey;
    })
    .AddJwtBearer(providerKey, config =>
    {
        config.RequireHttpsMetadata = false;
        config.TokenValidationParameters = tokenValidationParameters;
    });
    
  • Auth服务对登录接口强制校验JWT
    Auth服务的启动配置中将全局默认认证方案设为需要JWT校验的MY_SECRET_KEY,管道中开启了全局认证与授权逻辑,但登录动作方法没有添加匿名访问标记,即便网关放行请求,Auth服务也会因请求未携带JWT直接返回401。
    修复:给LoginAsync动作方法添加[AllowAnonymous]特性,跳过该接口的全局JWT校验。

  • 网关中间件执行顺序错误
    当前网关的管道顺序存在逻辑断层:UseOcelot直接放在管道末尾,且缺少UseAuthorization中间件,会导致认证流程逻辑不闭环,无法正常执行拦截逻辑;同时Configure方法使用async void返回值,会导致异步管道执行时出现未捕获的异常。
    修复:调整中间件顺序为ASP.NET Core与Ocelot要求的标准执行流:

    public async Task Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
    
        app.UseCors("CorsPolicy");
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
        
        await app.UseOcelot();
    }
    

内容的提问来源于stack exchange,提问作者Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.16 01:36:03