forked from xiongyuxing/tiku-backend.net
feat: add current user and tenant endpoints
This commit is contained in:
@@ -1,16 +1,23 @@
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Scalar.AspNetCore;
|
||||
using System.Text;
|
||||
using System.Text.Json.Serialization;
|
||||
using Tiku.Api.Middleware;
|
||||
using Tiku.Api.Security;
|
||||
using Tiku.Application;
|
||||
using Tiku.Application.Security;
|
||||
using Tiku.Infrastructure;
|
||||
using Tiku.Infrastructure.Persistence;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddControllers()
|
||||
.AddJsonOptions(options =>
|
||||
{
|
||||
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
|
||||
});
|
||||
builder.Services.AddOpenApi();
|
||||
builder.Services.AddProblemDetails();
|
||||
builder.Services.AddApplication();
|
||||
@@ -42,6 +49,36 @@ builder.Services
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.FromMinutes(1)
|
||||
};
|
||||
options.Events = new JwtBearerEvents
|
||||
{
|
||||
OnTokenValidated = async context =>
|
||||
{
|
||||
if (!jwtOptions.ValidateSessions)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var sessionIdValue = context.Principal?.FindFirst(TikuClaimTypes.SessionId)?.Value;
|
||||
if (!Guid.TryParse(sessionIdValue, out var sessionId))
|
||||
{
|
||||
context.Fail("Missing session claim.");
|
||||
return;
|
||||
}
|
||||
|
||||
var dbContext = context.HttpContext.RequestServices.GetRequiredService<TikuDbContext>();
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var isSessionActive = await dbContext.AuthSessions.AnyAsync(
|
||||
session =>
|
||||
session.Id == sessionId &&
|
||||
session.RevokedAt == null &&
|
||||
session.ExpiresAt > now);
|
||||
|
||||
if (!isSessionActive)
|
||||
{
|
||||
context.Fail("Session has been revoked or expired.");
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
builder.Services.AddAuthorization(options =>
|
||||
|
||||
Reference in New Issue
Block a user