What are JWT claims, and how do you add custom claims when issuing a token?
Short answer
Claims are key-value pairs embedded in a JWT's payload describing attributes about the authenticated subject (standard ones include sub, exp, iss, aud; custom ones might include role, tenant_id, or permissions).
Advertisement
AModel answer
Claims are key-value pairs embedded in a JWT's payload describing attributes about the authenticated subject (standard ones include sub, exp, iss, aud; custom ones might include role, tenant_id, or permissions). You add custom claims when constructing the token during login, and they become accessible via User.Claims or User.FindFirst() in any subsequently authenticated request.
var claims = new[] {
new Claim(JwtRegisteredClaimNames.Sub, user.Id),
new Claim("tenant_id", user.TenantId),
new Claim(ClaimTypes.Role, "Manager")
};
var token = new JwtSecurityToken(issuer, audience, claims,
expires: DateTime.UtcNow.AddHours(1),
signingCredentials: creds);
// Later, in any authorized endpoint:
var tenantId = User.FindFirst("tenant_id")?.Value;Real-world example
A multi-tenant SaaS application embeds a tenant_id claim in every issued JWT, letting every downstream authorized request efficiently scope database queries to the correct tenant without an extra database lookup.
Likely follow-ups
- What's the size trade-off of embedding many claims directly in a JWT?
- How do you handle claims that change frequently (like roles) with long-lived tokens?
Related topics