54 lines
1.8 KiB
C#
54 lines
1.8 KiB
C#
using Auth.Services;
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
builder.Services.AddControllers();
|
|
|
|
// DI
|
|
builder.Services.AddSingleton<UserService>();
|
|
builder.Services.AddSingleton<BlacklistService>();
|
|
|
|
// AuthN/JWT
|
|
var cfg = builder.Configuration;
|
|
var jwtKey = cfg["Jwt:Key"] ?? throw new Exception("Jwt:Key missing");
|
|
var issuer = cfg["Jwt:Issuer"] ?? "GameAuthApi";
|
|
var aud = cfg["Jwt:Audience"] ?? issuer;
|
|
|
|
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
|
.AddJwtBearer(o =>
|
|
{
|
|
o.TokenValidationParameters = new TokenValidationParameters
|
|
{
|
|
ValidateIssuer = true, ValidIssuer = issuer,
|
|
ValidateAudience = true, ValidAudience = aud,
|
|
ValidateIssuerSigningKey = true,
|
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
|
|
ValidateLifetime = true,
|
|
ClockSkew = TimeSpan.FromSeconds(30)
|
|
};
|
|
o.Events = new JwtBearerEvents
|
|
{
|
|
OnTokenValidated = async ctx =>
|
|
{
|
|
var jti = ctx.Principal?.FindFirstValue(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Jti);
|
|
if (!string.IsNullOrEmpty(jti))
|
|
{
|
|
var bl = ctx.HttpContext.RequestServices.GetRequiredService<BlacklistService>();
|
|
if (await bl.IsBlacklistedAsync(jti)) ctx.Fail("Token revoked");
|
|
}
|
|
}
|
|
};
|
|
});
|
|
|
|
builder.Services.AddAuthorization();
|
|
|
|
var app = builder.Build();
|
|
app.MapGet("/healthz", () => Results.Ok("ok"));
|
|
app.UseAuthentication();
|
|
app.UseAuthorization();
|
|
app.MapControllers();
|
|
app.Run();
|