0

I have an authentication scheme in my asp.net core web API that doesn't seem to work for some reason. This is where I define my middleware:

services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = true;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = jwtConfig.Issuer,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.Secret)),
                    ValidateAudience = true,
                    ValidAudience = jwtConfig.Audience,
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero

                };
            });

this is the relevant content of Config method:

app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

And this is how I create the token:

public string GenerateJwt (long userID,string userName)
        {
            var handler = new JwtSecurityTokenHandler();

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtconfig.Secret));
            var credentials = new SigningCredentials(securityKey,SecurityAlgorithms.HmacSha256);
            ClaimsIdentity claims = new ClaimsIdentity(new[]
            {
                new Claim("UserID",userID.ToString()),
                new Claim("UserName",userName),
            });
            var token = handler.CreateJwtSecurityToken(
                _jwtconfig.Issuer,
                _jwtconfig.Audience,
                new ClaimsIdentity(claims),
                null,
                DateTime.Now.AddMinutes(15),
                null,
                credentials);
            return  new JwtSecurityTokenHandler().WriteToken(token);
        }

I tried "shuffling" the order of the methods in Configure but still it doesn't work. Any help is appreciated!

Tabris
  • 37
  • 1
  • 5
  • Hi @Tabris, The correct order should be: `app.UseRouting();`, `app.UseAuthentication();`,`app.UseAuthorization();` and `app.UseEndpoints(...)`. It works well in my project. If still does not work, could you please share how do you send genertated jwt token to the authorized action? – Rena Oct 12 '21 at 09:00
  • @Rena I tried that order of methods and it still doesn't work. I didn't know I needed to manually send the token to action,I figured ` .WriteToToken()` and `[Authorize]` did that automatically :( – Tabris Oct 12 '21 at 09:55
  • Ok, I think you need check this answer :https://stackoverflow.com/a/65228648/11398810 and look carefully with the gif. – Rena Oct 12 '21 at 10:00

0 Answers0