mirror of
https://github.com/QuotifyTeam/QuotifyBE.git
synced 2025-12-16 14:20:06 +01:00
feat: jwt token example
This commit is contained in:
31
Program.cs
31
Program.cs
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user