(feature): custom jwt acl entry claim support

This commit is contained in:
Maksym Sadovnychyy 2025-10-16 20:37:31 +02:00
parent ab7fc58406
commit d121f045bd
5 changed files with 26 additions and 2 deletions

View File

@ -8,7 +8,7 @@
<!-- NuGet package metadata -->
<PackageId>MaksIT.Core</PackageId>
<Version>1.4.5</Version>
<Version>1.4.6</Version>
<Authors>Maksym Sadovnychyy</Authors>
<Company>MAKS-IT</Company>
<Product>MaksIT.Core</Product>

View File

@ -0,0 +1,12 @@
using MaksIT.Core.Abstractions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MaksIT.Core.Security.JWT;
public class CustomClaims : Enumeration {
public static readonly CustomClaims AclEntry = new(1, "acl_entry");
private CustomClaims(int id, string name) : base(id, name) { }
}

View File

@ -17,6 +17,8 @@ public class JWTTokenClaims {
/// </summary>
public List<string>? Roles { get; set; }
public List<string>? AclEntries { get; set; }
/// <summary>
/// Gets or sets the date and time when the token was issued.
/// </summary>

View File

@ -37,4 +37,7 @@ public class JWTTokenGenerateRequest {
/// </summary>
public List<string>? Roles { get; set; }
public List<string>? AclEntries { get; set; }
}

View File

@ -8,8 +8,10 @@ using System.Text;
namespace MaksIT.Core.Security.JWT;
public static class JwtGenerator {
public static class JwtGenerator {
/// <summary>
/// Attempts to generate a JWT token using the specified request parameters.
/// </summary>
@ -49,6 +51,9 @@ public static class JwtGenerator {
if (request.Roles !=null)
claims.AddRange(request.Roles.Select(role => new Claim(ClaimTypes.Role, role)));
if (request.AclEntries != null)
claims.AddRange(request.AclEntries.Select(acl => new Claim(CustomClaims.AclEntry.Name, acl)));
var tokenDescriptor = new JwtSecurityToken(
issuer: request.Issuer,
audience: request.Audience,
@ -141,6 +146,7 @@ public static class JwtGenerator {
var username = principal.Identity?.Name;
var roles = principal.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => c.Value).ToList();
var aclEntries = principal.Claims.Where(c => c.Type == CustomClaims.AclEntry.Name).Select(c => c.Value).ToList();
var issuedAtClaim = principal.Claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Iat)?.Value;
var expiresAtClaim = principal.Claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Exp)?.Value;
@ -152,6 +158,7 @@ public static class JwtGenerator {
UserId = userId,
Username = username,
Roles = roles,
AclEntries = aclEntries,
IssuedAt = issuedAt,
ExpiresAt = expiresAt
};