Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is 'JwtBearerDefaults.AuthenticationScheme' and 'JwtBearerDefaults' for?

Tags:

c#

.net

asp.net

What exactly is the call JwtBearerDefaults.AuthenticationScheme and JwtBearerDefaults for?

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidIssuer = tokenOptions.Issuer,
        ValidAudience = tokenOptions.Audience,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = SecurityKeyHelper.CreateSecurityKey(tokenOptions.SecurityKey)
    };
});
like image 397
Burcu Taş Avatar asked Dec 17 '25 05:12

Burcu Taş


1 Answers

JwtBearerDefaults.AuthenticationScheme is a constant with the value "Bearer". This is just text that is similar in intent to the authentication provider.

When you call AddAuthentication, you need to provide the default authentication provider. Providers are named. By default AddJwtBearer will create an authentication provider with the name, yep you guessed it, JwtBearerDefaults.AuthenticationScheme.

You could ignore the JwtBearerDefaults class altogether if you'd like. Pass whatever string you want to AddAuthentication, then use the overload of AddJwtBearer that takes a string and an Action to customize the provider's name. This is useful if you are using multiple of the same authentication scheme (you have two .AddJwtBearer() with different options, for example).

builder.Services.AddAuthentication("MyCoolAuthProvider")
.AddJwtBearer("MyCoolAuthProvider", options => {
    //...
});

In the end, why do people use the JwtBearerDefaults class? Same reason you name your for loop variable i. It's what the documentation suggests, and everyone else does it. At least if it's a constant, you can't typo the value.

like image 124
gunr2171 Avatar answered Dec 20 '25 04:12

gunr2171



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!