Files
flatrender/services/identity/FlatRender.IdentitySvc/Application/Services/TokenService.cs
T
soroush.asadi 90ac0b81d1 feat: V2 microservices stack — backend services, gateway, JWT auth
Add full V2 architecture: identity, content, studio (.NET 10) and file,
render, notification, gateway (Go) services with vendored deps, plus DB
migrations, event/API contracts, and an init-db script.

Wire the Next.js frontend to the gateway: server-side JWT auth routes
(login/register/refresh/logout/me), gateway fetch helper, and session/
cookie/jwt helpers under src/lib.

Containerize the stack via docker-compose.v2.yml and per-service
Dockerfiles. Base images resolve through a Nexus mirror (Docker Hub) and
MCR directly; npm/NuGet pull from Nexus groups. Self-host fonts via
next/font/local to avoid Google Fonts (geo-blocked).

Add CI workflow and ignore .env.v2, *.stackdump, and .NET bin/obj.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 23:29:31 +03:30

96 lines
3.6 KiB
C#

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using FlatRender.IdentitySvc.Application.Services.Interfaces;
using FlatRender.IdentitySvc.Domain.Entities;
using Microsoft.IdentityModel.Tokens;
namespace FlatRender.IdentitySvc.Application.Services;
public class TokenService(IConfiguration config) : ITokenService
{
private readonly string _secret = config["Jwt:Secret"]
?? throw new InvalidOperationException("Jwt:Secret not configured");
private readonly string _issuer = config["Jwt:Issuer"] ?? "flatrender-identity";
private readonly string _audience = config["Jwt:Audience"] ?? "flatrender";
private readonly int _accessTokenMinutes = int.Parse(config["Jwt:AccessTokenMinutes"] ?? "15");
public string GenerateAccessToken(User user, Tenant tenant)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secret));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var claims = new List<Claim>
{
new(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new("tenant_id", tenant.Id.ToString()),
new("tenant_slug", tenant.Slug),
new("is_admin", user.IsAdmin.ToString().ToLower()),
new("is_tenant_admin", user.IsTenantAdmin.ToString().ToLower()),
};
if (!string.IsNullOrEmpty(user.Email))
claims.Add(new(JwtRegisteredClaimNames.Email, user.Email));
var token = new JwtSecurityToken(
issuer: _issuer,
audience: _audience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(_accessTokenMinutes),
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
public string GenerateRefreshToken()
=> Convert.ToBase64String(RandomNumberGenerator.GetBytes(64));
public string HashToken(string token)
{
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(token));
return Convert.ToHexString(bytes).ToLower();
}
public (Guid userId, Guid tenantId, bool isAdmin) ValidateAccessToken(string token)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secret));
var handler = new JwtSecurityTokenHandler();
var parameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = key,
ValidateIssuer = true,
ValidIssuer = _issuer,
ValidateAudience = true,
ValidAudience = _audience,
ValidateLifetime = true,
};
var principal = handler.ValidateToken(token, parameters, out _);
var userId = Guid.Parse(principal.FindFirstValue(JwtRegisteredClaimNames.Sub)!);
var tenantId = Guid.Parse(principal.FindFirstValue("tenant_id")!);
var isAdmin = bool.Parse(principal.FindFirstValue("is_admin") ?? "false");
return (userId, tenantId, isAdmin);
}
public string GenerateServiceToken()
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secret));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _issuer,
audience: _audience,
claims: [new("type", "service"), new("service", "identity")],
expires: DateTime.UtcNow.AddHours(24),
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}