From ffdf99792950aa271da45be798487330de9e6aa7 Mon Sep 17 00:00:00 2001 From: Blitblank Date: Tue, 21 Apr 2026 20:32:48 -0500 Subject: [PATCH] add roles to jwt claims --- api/src/Controllers/AuthController.cs | 2 +- api/src/Services/JwtService.cs | 13 ++++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/api/src/Controllers/AuthController.cs b/api/src/Controllers/AuthController.cs index bc84737..47c2343 100644 --- a/api/src/Controllers/AuthController.cs +++ b/api/src/Controllers/AuthController.cs @@ -97,7 +97,7 @@ public class AuthController : ControllerBase { User? user = await jwt_.GetUser(storedToken.UserId); if(user == null) return NotFound(); - string? newAccessToken = jwt_.GenerateJwt(user); + string? newAccessToken = await jwt_.GenerateJwt(user); if(newAccessToken == null) return NotFound(); string newRefreshToken = jwt_.GenerateRefreshToken(); diff --git a/api/src/Services/JwtService.cs b/api/src/Services/JwtService.cs index 54f1c15..093c792 100644 --- a/api/src/Services/JwtService.cs +++ b/api/src/Services/JwtService.cs @@ -5,6 +5,7 @@ using System.Text; using System.Security.Claims; using System.IdentityModel.Tokens.Jwt; using System.Security.Cryptography; +using Microsoft.AspNetCore.Identity; using agologumApi.Models; @@ -12,13 +13,15 @@ public class JwtService { private readonly IConfiguration config_; private readonly AppDbContext db_; + private readonly UserManager userManager_; - public JwtService(IConfiguration config, AppDbContext db) { // why the heck does c# not have initializer lists ? + public JwtService(IConfiguration config, AppDbContext db, UserManager userManager) { // why the heck does c# not have initializer lists ? config_ = config; db_ = db; + userManager_ = userManager; } - public string? GenerateJwt(User user) { + public async Task GenerateJwt(User user) { string? jwtKey = config_["Jwt:Key"]; if(jwtKey == null) return null; @@ -28,12 +31,16 @@ public class JwtService { if(user.UserName == null) return null; + var roles = await userManager_.GetRolesAsync(user); + // not too sure - var claims = new[] { + var claims = new List { new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()) }; + claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role))); + var token = new JwtSecurityToken( issuer: "agologum", audience: "agologum",