Helper Method to get User Info from Claims in C#

ebeeraheem

View Profile
16 views
Jun 21, 2025
public class UserHelper(IHttpContextAccessor httpContextAccessor)
{
   public string GetUserId()
   {
       return httpContextAccessor.HttpContext?.User
           .FindFirst(ClaimTypes.NameIdentifier)?.Value
           ?? throw new InvalidOperationException("User ID not found in claims.");
   }

   public string GetUserEmail()
   {
       return httpContextAccessor.HttpContext?.User
           .FindFirst(ClaimTypes.Email)?.Value
           ?? throw new InvalidOperationException("User email not found in claims.");
   }

   public string GetUserName()
   {
       return httpContextAccessor.HttpContext?.User
           .FindFirst(ClaimTypes.Name)?.Value
           ?? throw new InvalidOperationException("User name not found in claims.");
   }

   public string GetUserRole()
   {
       return httpContextAccessor.HttpContext?.User
           .FindFirst(ClaimTypes.Role)?.Value
           ?? throw new InvalidOperationException("User role not found in claims.");
   }

   public string GetIpAddress()
   {
       return httpContextAccessor.HttpContext?.Connection?.RemoteIpAddress?.ToString()
           ?? throw new InvalidOperationException("IP address not found.");
   }

   public bool IsAuthenticated()
   {
       return httpContextAccessor.HttpContext?.User
           .Identity?.IsAuthenticated ?? false;
   }
}