简体   繁体   中英

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.

I installed jwt packages ocelot and auth servers. When I try to log in, it returns 401. So, this part of my application is wrong. What is wrong with my code? These are my codes;

ocelot.json

I added the AuthenticationOptions key to the ocelot file.

"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

I implement jwt for api gateway

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

After, I set up JWT for my auth server.

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

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?

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 ;

        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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