Home > database >  What exactly is 'JwtBearerDefaults.AuthenticationScheme' and 'JwtBearerDefaults'
What exactly is 'JwtBearerDefaults.AuthenticationScheme' and 'JwtBearerDefaults'

Time:07-09

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)
    };
});

CodePudding user response:

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, this is personal preference. 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.

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.

  • Related