简体   繁体   English

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

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

I'm trying to implement the microservice architecture.我正在尝试实现微服务架构。 I'm using ASP.NET Core 3.1 API to implement.我正在使用 ASP.NET Core 3.1 API 来实现。

I installed jwt packages ocelot and auth servers.我安装了 jwt 包 ocelot 和 auth 服务器。 When I try to log in, it returns 401. So, this part of my application is wrong.当我尝试登录时,它返回 401。所以,我的应用程序的这部分是错误的。 What is wrong with my code?我的代码有什么问题? These are my codes;这些是我的代码;

ocelot.json豹猫.json

I added the AuthenticationOptions key to the ocelot file.我在 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 Gateway Startup.cs API 网关启动.cs

I implement jwt for api gateway我为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();
            //});
        }

Auth Server Startup.cs身份验证服务器启动.cs

After, I set up JWT for my auth server.之后,我为我的身份验证服务器设置了 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's LoginAsync Action AuthController 的 LoginAsync 操作

I can't even send requests here.我什至不能在这里发送请求。

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

This is the screenshot for the response;这是响应的屏幕截图;

示例截图

I don't understand why I'm getting 401?我不明白为什么我会收到 401?

I think the problem is:我认为问题是:

services.AddAuthentication()

Change your code like this:像这样更改您的代码:

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.

相关问题 将 Ocelot 16.0 与 ASP.Net Core 3.1 集成不起作用,因为我需要将 Swagger 与 Ocelot 一起使用 - Integrating Ocelot 16.0 with ASP.Net Core 3.1 not working as I need to use Swagger with Ocelot ASP.Net Core 3 API 总是返回 401-JwtBearer - ASP.Net Core 3 API always returns 401- JwtBearer ASP.NET Core 3.1 Web API 中的“授权失败。AuthenticationScheme:AzureADJwtBearer 受到挑战” - 401 Unauthorized - "Authorization failed. AuthenticationScheme: AzureADJwtBearer was challenged" in ASP.NET Core 3.1 Web API - 401 Unauthorized Asp .net core 3.1 JWT和SignalR认证登录部分 - Asp .net core 3.1 JWT and SignalR authentication login part 不记名令牌出现 401 错误 - asp.net 核心 3.1 - 401 error with bearer token - asp.net core 3.1 ASP.NET 内核 Jwt 401 未经授权。 策略认证 - ASP.NET Core Jwt 401 Unauthorized. Policy auth 在测试 ASP.Net Core 3.1 Web Api 期间跳过 JWT Auth - Skip JWT Auth during Tests ASP.Net Core 3.1 Web Api ASP.NET 核心 - JWT 授权总是抛出 401 - ASP.NET Core - JWT authorization always throws 401 ASP.NET Core 5 JWT 身份验证失败,响应代码为 401 - ASP.NET Core 5 JWT Authentication fails with response code 401 使用两个JWT Authentication Scheme,ASP.NET Core 3.1 - Use two JWT Authentication Scheme, ASP.NET Core 3.1
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM