ARTICLE AD BOX
I'm working on an ASP.NET Core Web API with JWT authentication. I generate a token that includes a custom claim EmployeeId, and I try to read it inside my controller, but it is always returned as null or 0.
JWT generation (JwtService):
public string GenerateAccessToken(User user, IEnumerable<string> roles, IEnumerable<string> permissions, int employeeId) { var secretKey = _config["Jwt:Key"] ?? "I_AM_2026"; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var claims = new List<Claim> { new Claim(ClaimTypes.Name, user.Username), new Claim("UserId", user.Id.ToString()), new Claim("EmployeeId", employeeId.ToString()) }; if (roles != null && roles.Any()) claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role))); var token = new JwtSecurityToken( issuer: _config["Jwt:Issuer"] ?? "Backend", audience: _config["Jwt:Audience"] ?? "Frontend", claims: claims, expires: DateTime.UtcNow.AddHours(8), signingCredentials: creds ); return new JwtSecurityTokenHandler().WriteToken(token); }Controller:
[ApiController] [Route("api/[controller]")] public class AttendanceController : ControllerBase { private int CurrentEmployeeId => int.Parse(User.FindFirst("EmployeeId")?.Value ?? "0"); protected int GetEmployeeId() { var claim = User.FindFirst("EmployeeId")?.Value; return int.TryParse(claim, out int id) ? id : 0; } [HttpGet("daily")] public async Task<IActionResult> GetDaily(DateTime? date) { var empId = GetEmployeeId(); if (empId <= 0) return Unauthorized("EmployeeId claim missing or invalid."); var records = await _service.Daily(date ?? DateTime.Today, empId, "Employee"); return Ok(records); } }Problem
User.FindFirst("EmployeeId") returns null GetEmployeeId() returns 0 I confirmed the claim exists when generating the tokenWhat I have tried:
Checked token generation Confirmed claim is added Tested with PostmanQuestions
Why is the "EmployeeId" claim not available in the controller? Do I need to configure something in Program.cs or JWT middleware for custom claims? Is there a better way to handle custom claims in ASP.NET Core?Additional info:
Using ASP.NET Core Web API JWT Bearer authentication Token is sent via Authorization: Bearer <token>Any help would be appreciated.
