JWT token authentication not working When upgrading .net 5.0 to .net 6.0

Viewed 75

I have converted .net 5.0 Web API to .net 6.0 Web API.The JWT Authorization was working fine in 5.0.When I change "startup.cs" to "program.cs" then I am getting "Unauthorized" error. Please check below code for "program.cs" and advise where it is problem.

Note:-

all API working fine without authorize

  var builder = WebApplication.CreateBuilder(args);
var provider = builder.Services.BuildServiceProvider();
var Configuration = provider.GetRequiredService<IConfiguration>();


builder.Services.AddCors(options =>
{
    options.AddPolicy(
        "Open",
        builder => builder.AllowAnyOrigin().AllowAnyHeader());
});

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "tEST.Services", Version = "v1" });
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "JWT Authorization",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer"
    });
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference= new OpenApiReference
                            {
                                Type= ReferenceType.SecurityScheme,
                                Id="Bearer"
                            }
                        }, new string[] { }

                    }
                });
});

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
              .AddJwtBearer(options =>
              {
                  options.TokenValidationParameters = new TokenValidationParameters
                  {
                      ValidateIssuer = true,
                      ValidateAudience = true,
                      ValidateLifetime = true,
                      ValidateIssuerSigningKey = true,
                      ValidIssuer = Configuration["Jwt:Issuer"],
                      ValidAudience = Configuration["Jwt:Audience"],
                      IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                  };

                  options.Events = new JwtBearerEvents
                  {
                      OnAuthenticationFailed = context =>
                      {
                          if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                          {
                              context.Response.Headers.Add("Token-Expired", "true");
                          }
                          return Task.CompletedTask;
                      }
                  };
              });

builder.Services.AddSingleton<IConfiguration>(Configuration);
1 Answers

I had the same problem. In my case it was an issue with package versions . I updated Microsoft.AspNetCore.Authentication.JwtBearer to version 6.0.0, but didn't update the version of packages System.IdentityModel.Tokens.Jwt, Microsoft.IdentityModel.Tokens, and Microsoft.IdentityModel.JsonWebTokens.

In my case there was two possible solutions:

  1. Update all the packages to the (current) latest version:
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.9"/>
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.23.1"/>
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.23.1"/>
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" Version="6.23.1"/>
  1. Simply remove any explicit reference to packages System.IdentityModel.Tokens.Jwt, Microsoft.IdentityModel.Tokens, or Microsoft.IdentityModel.JsonWebTokens from the .csproj file, clear the Nuget cache, delete the build/Debug folder, and then rebuild the project.

These two links were useful for identifying the root cause:

Related