Inject roles on token validation

This commit is contained in:
lumijiez
2025-06-08 00:17:01 +03:00
parent 87c4f27de5
commit ab9b80b74f
12 changed files with 137 additions and 38 deletions

View File

@@ -1,5 +1,3 @@
using System.Security.Claims;
using Imprink.Domain.Common.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
@@ -15,16 +13,11 @@ public class UserController : ControllerBase
{
var claims = User.Claims;
var enumerable = claims as Claim[] ?? claims.ToArray();
var user = new Auth0User
foreach (var claim in claims)
{
Sub = enumerable.FirstOrDefault(c => c.Type == "sub")?.Value ?? "",
Name = enumerable.FirstOrDefault(c => c.Type == "name")?.Value ?? "",
Nickname = enumerable.FirstOrDefault(c => c.Type == "nickname")?.Value ?? "",
Email = enumerable.FirstOrDefault(c => c.Type == "email")?.Value ?? "",
EmailVerified = enumerable.FirstOrDefault(c => c.Type == "email_verified")?.Value == "true"
};
return Ok(user);
Console.WriteLine($"Claim Type: {claim.Type}, Claim Value: {claim.Value}");
}
return Ok("Claims logged to console.");
}
}

View File

@@ -1,3 +1,4 @@
using System.Security.Claims;
using Imprink.Application;
using Imprink.Application.Products.Create;
using Imprink.Domain.Repositories;
@@ -41,6 +42,34 @@ public static class Startup
{
options.Authority = builder.Configuration["Auth0:Authority"];
options.Audience = builder.Configuration["Auth0:Audience"];
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var token = context.Request.Cookies["access_token"];
if (!string.IsNullOrEmpty(token)) context.Token = token;
return Task.CompletedTask;
},
OnTokenValidated = context =>
{
var dbContext = context.HttpContext.RequestServices.GetService<ApplicationDbContext>();
var userId = context.Principal?.FindFirst(ClaimTypes.NameIdentifier)?.Value
?? context.Principal?.FindFirst("sub")?.Value;
if (string.IsNullOrEmpty(userId)) return Task.CompletedTask;
var identity = context.Principal!.Identity as ClaimsIdentity;
var roles = (from ur in dbContext?.UserRole
join r in dbContext?.Roles on ur.RoleId equals r.Id
where ur.UserId == userId
select r.RoleName).ToList();
foreach (var role in roles) identity!.AddClaim(new Claim(ClaimTypes.Role, role));
return Task.CompletedTask;
}
};
});
services.AddAuthorization();