Autorize with JWT Authentication

samir karim 20 Reputation points
2024-05-05T12:16:18.61+00:00

Hello,

i want to use JWT Authentication in an App using .net 8

so i have configured Program.cs like this:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(

authenticationScheme: JwtBearerDefaults.AuthenticationScheme,

configureOptions:options =>

{

options.RequireHttpsMetadata = false;

options.SaveToken = true;

//options.Audience = "http://localhost:5001/";

//options.Authority = "http://localhost:5000/";

options.TokenValidationParameters = new TokenValidationParameters

{

ValidIssuer = jwtIssuer,

ValidAudience = jwtAudience,

IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),

ValidateIssuer = true,

ValidateAudience = true,

ValidateLifetime = true,

ValidateIssuerSigningKey = true,

//ClockSkew = TimeSpan.Zero

};

});

and for Authorize Api :

[HttpGet("apiGetProducts")]

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

public async Task<ActionResult> GetProducts()

{

return Ok(await _Repository.GetProducts());

}

and Appsettings:

"jwt": {

"key": "** * * ** *",

//Front

"Issuer": "https://localhost:5027",

//API

"Audience": "https://localhost:7173",

"Subject": "* * * * * * *",

"Secret": "* * * * * * "

},

and everything work Good, but then, i tried to change values in Apssettings Json file , and i changed Issuer and Audience values,

so normally, the app wil have a Bug(Unauthorize)

BUT

for my case , the app still work even i changed Issuer and Adience Values

any idea ?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,226 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Martinho Sebastião 0 Reputation points
    2024-05-05T19:44:32.42+00:00

    Hello,

    when you make changes to appsettings.json you must restart the application or API so that the new settings are applied. Or you can configure it to do an auto-restart whenever it detects changes, see the example:

     var builder = new ConfigurationBuilder()
                           .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                           .AddEnvironmentVariables();
    

    Don't forget to generate a new token.

    0 comments No comments