繁体   English   中英

ASP.NET Core 3.1 API Ocelot JWT 在登录时返回 401

[英]ASP.NET Core 3.1 API Ocelot JWT Returns 401 on Login

我正在尝试实现微服务架构。 我正在使用 ASP.NET Core 3.1 API 来实现。

我安装了 jwt 包 ocelot 和 auth 服务器。 当我尝试登录时,它返回 401。所以,我的应用程序的这部分是错误的。 我的代码有什么问题? 这些是我的代码;

豹猫.json

我在 ocelot 文件中添加了 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": []
      }
    }
  ]

API 网关启动.cs

我为api网关实现了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();
            //});
        }

身份验证服务器启动.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();
            });
        }

AuthController 的 LoginAsync 操作

我什至不能在这里发送请求。

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

这是响应的屏幕截图;

示例截图

我不明白为什么我会收到 401?

我认为问题是:

services.AddAuthentication()

像这样更改您的代码:

services.AddAuthentication(option =>
        {
            option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(providerKey ,option =>
        {
            option.RequireHttpsMetadata = false;
            option.SaveToken = true;
            option.TokenValidationParameters = tokenValidationParameters ;

        });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM