Add JWT authentication.
Add: JWT authentication in Web API. Related configuration and services are added.
This commit is contained in:
@ -1,6 +1,10 @@
|
||||
using System.CommandLine;
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using OptixServe.Api.Configuration;
|
||||
using OptixServe.Api.Endpoints;
|
||||
using OptixServe.Api.Services;
|
||||
using OptixServe.Core.Data;
|
||||
using OptixServe.Core.Services;
|
||||
using OptixServe.Api.Utilites;
|
||||
@ -50,6 +54,9 @@ class Program
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
var initializer = scope.ServiceProvider.GetRequiredService<DbInitializer>();
|
||||
@ -127,6 +134,25 @@ static class StartupHelper
|
||||
|
||||
// Application services
|
||||
builder.Services.AddScoped<IUserService, UserService>();
|
||||
builder.Services.AddScoped<ITokenService, TokenService>();
|
||||
|
||||
// Add Authentication and Authorization
|
||||
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
var jwtSettings = onConfigSettings?.Jwt ?? throw new ArgumentNullException(nameof(builder), "JWT settings are not configured.");
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = jwtSettings.Issuer,
|
||||
ValidAudience = jwtSettings.Audience,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Secret))
|
||||
};
|
||||
});
|
||||
builder.Services.AddAuthorization();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
Reference in New Issue
Block a user