feat: jwt token example

This commit is contained in:
2025-07-15 10:22:53 +02:00
parent c277b190e6
commit b6dc1ce2cd
5 changed files with 103 additions and 1 deletions

View File

@@ -1,6 +1,9 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using QuotifyBE.Data;
using QuotifyBE.Entities;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
@@ -9,7 +12,34 @@ var connectionString = builder.Configuration.GetConnectionString("DefaultConnect
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(connectionString));
var JwtSecret = builder.Configuration["JwtSecret"]
?? throw new InvalidOperationException("JWT token secret is not configured!!! Please configure JwtSecret in appsettings.json!");
var DomainName = builder.Configuration["DomainName"]
?? throw new InvalidOperationException("Domain name is not configured!!! Please configure DomainName in appsettings.json!");
// Configure JWT authentication
// https://medium.com/@solomongetachew112/jwt-authentication-in-net-8-a-complete-guide-for-secure-and-scalable-applications-6281e5e8667c
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = DomainName,
ValidAudience = DomainName,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(JwtSecret)
)
};
});
// Add services to the container.
builder.Services.AddAuthorization();
builder.Services.AddSingleton(builder.Configuration);
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
@@ -28,6 +58,7 @@ if (app.Environment.IsDevelopment())
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();