c6918cbeea
JWTs were previously fully stateless -- the token alone was the credential until its own expiry, with no way to list or kill a session server-side. Add a UserSession table alongside every JWT issued (AppSessionIssuer), embed its id as a "sid" claim, and check that claim against the DB on every "local" scheme request (Program.cs OnTokenValidated) so a session can actually be revoked before its JWT naturally expires. New /api/auth/sessions endpoints (list, revoke one, revoke-others) plus a Sessions card on the profile page. Fails closed on a missing "sid" claim: every JWT issued going forward has one, so a token without it is either pre-deploy (forces one re-login for already-signed-in users at deploy time, same additive-forward cost the 2FA/trusted-device work on this branch already paid) or forged.
77 lines
2.5 KiB
C#
77 lines
2.5 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
using JobTrackerApi.Models;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
namespace JobTrackerApi.Services;
|
|
|
|
public interface ITokenService
|
|
{
|
|
Task<string> CreateAccessTokenAsync(ApplicationUser user, string? sessionId = null, CancellationToken cancellationToken = default);
|
|
}
|
|
|
|
public sealed class TokenService : ITokenService
|
|
{
|
|
private readonly IConfiguration _cfg;
|
|
private readonly UserManager<ApplicationUser> _users;
|
|
|
|
public TokenService(IConfiguration cfg, UserManager<ApplicationUser> users)
|
|
{
|
|
_cfg = cfg;
|
|
_users = users;
|
|
}
|
|
|
|
public async Task<string> CreateAccessTokenAsync(ApplicationUser user, string? sessionId = null, CancellationToken cancellationToken = default)
|
|
{
|
|
var jwtKey = (_cfg["Auth:JwtKey"] ?? "").Trim();
|
|
if (string.IsNullOrWhiteSpace(jwtKey))
|
|
{
|
|
throw new InvalidOperationException("Auth:JwtKey is not configured.");
|
|
}
|
|
|
|
var issuer = (_cfg["Auth:JwtIssuer"] ?? "JobTrackerApi").Trim();
|
|
var audience = (_cfg["Auth:JwtAudience"] ?? "job-tracker-ui").Trim();
|
|
|
|
var minutes = _cfg.GetValue("Auth:JwtExpiresMinutes", 60 * 12);
|
|
if (minutes < 5) minutes = 5;
|
|
if (minutes > 60 * 24 * 30) minutes = 60 * 24 * 30;
|
|
|
|
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey));
|
|
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
|
|
|
var roles = await _users.GetRolesAsync(user);
|
|
|
|
var claims = new List<Claim>
|
|
{
|
|
new(ClaimTypes.NameIdentifier, user.Id),
|
|
};
|
|
|
|
if (!string.IsNullOrWhiteSpace(user.Email))
|
|
claims.Add(new Claim(ClaimTypes.Email, user.Email));
|
|
if (!string.IsNullOrWhiteSpace(user.UserName))
|
|
claims.Add(new Claim(ClaimTypes.Name, user.UserName));
|
|
|
|
foreach (var r in roles)
|
|
claims.Add(new Claim(ClaimTypes.Role, r));
|
|
|
|
if (!string.IsNullOrWhiteSpace(sessionId))
|
|
claims.Add(new Claim("sid", sessionId));
|
|
|
|
var now = DateTime.UtcNow;
|
|
|
|
var token = new JwtSecurityToken(
|
|
issuer: issuer,
|
|
audience: audience,
|
|
claims: claims,
|
|
notBefore: now.AddSeconds(-5),
|
|
expires: now.AddMinutes(minutes),
|
|
signingCredentials: creds
|
|
);
|
|
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
}
|
|
}
|