'Why is my JWT token not allowing me to access an authorized endpoint in .NET Core WEB API 6?

I can login and generate a token successfully, but when I make a request to an endpoint that requires authorization and pass in my token, I still get a 401 response in Postman.

Here is my Program code:

global using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;



var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
builder.Services.AddDbContext<DataContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.RequireHttpsMetadata = false;
    options.SaveToken = true;
    options.TokenValidationParameters = new TokenValidationParameters()
    {
        ClockSkew = TimeSpan.MaxValue,
        ValidateLifetime = false,
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidAudience = builder.Configuration["AppSettings:Audience"],
        ValidIssuer = builder.Configuration["AppSettings:Issuer"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["AppSettings:Token"]))
    };
    
});


builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

app.UseAuthentication();

app.UseAuthorization();

app.UseHttpsRedirection();

app.MapControllers();

app.Run();

And here is where I generate the token.

        public async Task<ActionResult<string>> Login([FromBody] UserDto request)
        {
            var userToLogin = await _context.Users.Where(u => u.username == request.username).FirstOrDefaultAsync();
            if(userToLogin == null)
            {
                return BadRequest("User not found.");
            }

            if(userToLogin.username != request.username)
            {
                return BadRequest("Wrong username.");
            }

            if (!verifyPasswordHash(request.password, userToLogin.password))
            {
                return BadRequest("Wrong password");
            }
            string token = createToken(request.username);
            return Ok(token);
        }

        private string createToken(string username)
        {
            List<Claim> claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, username)
            };

            var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_configuration.GetSection("AppSettings:Token").Value));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var token = new JwtSecurityToken(claims: claims, signingCredentials: creds, expires: DateTime.MaxValue);

            var jwt = new JwtSecurityTokenHandler().WriteToken(token);

            return jwt;
        }

And here's my appsettings.json file:

    "DefaultConnection": "server=localhost\\sqlexpress;database=poetrydb;trusted_connection=true"
  },
  "AppSettings": {
    "Token": "sakdkvsksjwasjaiao3949cksqoqo39c9dj4e",
    "Issuer": "JWTAuthenticationServer",
    "Audience":  "JWTServicePostmanClient"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Any help would be appreciated.



Solution 1:[1]

I fixed the problem. I was not passing in the token secret to the .AddJwtBearer method. After passing it in, my program works as expected.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 malayze