I'm going to use JWT Bearer Authorization for my site. But the configuration of this takes a lot of place in the Startup.cs
. I decided that I need to create something like extension method in a static class to make my Startup.cs
more readable. Here is the code of this extension method:
public static IServiceCollection AddAuthenticationWithBearer(this IServiceCollection services,
IConfiguration configuration)
{
services.Configure<AuthOptions>(configuration.GetSection("JwtOptions"));
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<IJwtService, JwtService>();
// Can I use already mapped AuthOptions instead of this ???
var jwtConfigurationSection = configuration.GetSection("JwtOptions");
services.AddAuthentication().AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = jwtConfigurationSection.GetValue<bool>("ValidateIssuer"),
ValidIssuer = jwtConfigurationSection.GetValue<string>("ValidIssuer"),
ValidateAudience = jwtConfigurationSection.GetValue<bool>("ValidateAudience"),
ValidAudience = jwtConfigurationSection.GetValue<string>("ValidAudience"),
ValidateLifetime = jwtConfigurationSection.GetValue<bool>("ValidateLifetime"),
IssuerSigningKey =
new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration["AuthJwtSecret"])),
ValidateIssuerSigningKey = jwtConfigurationSection.GetValue<bool>("ValidateIssuerSigningKey"),
};
});
services.AddAuthorization();
return services;
}
My main problem under the comment. I know about convenient mechanism with services.Configure<AuthOptions>(configuration.GetSection("JwtOptions"));
. So, section 'JwtOptions' from appsettings.json
is mapped on AuthOptions
class. But I have no idea how I can use this here! As you can see, I have the call of configuration.GetSection("JwtOptions");
here, but I don't like it. I would like to use mapped AuthOptions
class. I think you understand my reasons: 1) If I will change appsettings.json
- I have only one place where I should to think about changes. It's AuthOptions
. Next - IDE will highlight the rest. 2) I want to have only one way to getting configurations from appsettings.json
. And I like the way with mapped class like AuthOptions
.