- Create ControllerBaseExtensions.TryGetUserId() - Replace 8 occurrences of manual ClaimTypes.NameIdentifier parsing - Same namespace (Heimdall.Api.Controllers) as existing controllers
22 lines
721 B
C#
22 lines
721 B
C#
using System.Security.Claims;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
namespace Heimdall.Api.Controllers;
|
|
|
|
/// <summary>
|
|
/// Extension methods for ControllerBase providing common user identity extraction
|
|
/// from JWT claims, reducing boilerplate in API controllers.
|
|
/// </summary>
|
|
public static class ControllerBaseExtensions
|
|
{
|
|
/// <summary>
|
|
/// Tries to get the current user's GUID from the NameIdentifier claim.
|
|
/// Returns true and sets userId if the claim is valid.
|
|
/// </summary>
|
|
public static bool TryGetUserId(this ControllerBase controller, out Guid userId)
|
|
{
|
|
var claim = controller.User.FindFirstValue(ClaimTypes.NameIdentifier);
|
|
return Guid.TryParse(claim, out userId);
|
|
}
|
|
}
|