ASP.NET Core Interview Question #131
What is ClaimsPrincipal in ASP.NET Core?
Authentication, Authorization & Security Mid-Level Intermediate
Quick Interview Answer
ClaimsPrincipal represents the current security principal and can contain one or more ClaimsIdentity objects. Each identity contains claims describing the subject, such as name, user identifier, role, permission, or other attributes.
Detailed Explanation
ClaimsPrincipal represents the current security principal and can contain one or more ClaimsIdentity objects. Each identity contains claims describing the subject, such as name, user identifier, role, permission, or other attributes.
In an HTTP request, the current principal is normally available through HttpContext.User and Controller.User. Authorization policies evaluate this principal to decide whether access requirements are met.
Code Example
var user = HttpContext.User;
if (user.Identity?.IsAuthenticated == true)
{
var name = user.Identity.Name;
var userId = user.FindFirst(ClaimTypes.NameIdentifier)?.Value;
}