I was able to implement the below JWT solution in my MVC WebApi following below link JWT Authentication for Asp.Net Web Api
Now, I want to access claim in the controllers, but all claims are null. I have tried a few things and all of them returns null.
How is claim added in JwtAuthenticationAttribute:
protected Task<IPrincipal> AuthenticateJwtToken(string token)
{
string username;
if (ValidateToken(token, out username))
{
//Getting user department to add to claim.
eTaskEntities _db = new eTaskEntities();
var _user = (from u in _db.tblUsers join d in _db.tblDepartments on u.DepartmentID equals d.DepartmentID select u).FirstOrDefault();
var department = _user.DepartmentID;
// based on username to get more information from database in order to build local identity
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.SerialNumber, department.ToString())
// Add more claims if needed: Roles, ...
};
var identity = new ClaimsIdentity(claims, "Jwt");
IPrincipal user = new ClaimsPrincipal(identity);
return Task.FromResult(user);
}
return Task.FromResult<IPrincipal>(null);
}
What I have tried so far
Extension method to get claim:
public static class IPrincipleExtension
{
public static String GetDepartment(this IIdentity principal)
{
var identity = HttpContext.Current.User.Identity as ClaimsIdentity;
if (identity != null)
{
return identity.FindFirst("SerialNumber").Value;
}
else
return null;
}
}
Using the function defined in the post (link above):
TokenManager.GetPrincipal(Request.Headers.Authorization.Parameter).FindFirst("SerialNumber")
Trying to access Claim through thread:
((ClaimsPrincipal)System.Threading.Thread.CurrentPrincipal.Identity).FindFirst("SerialNumber")
For all the above, a claim is always null. What am I doing wrong?