how to validate jwt token in web api c# code example
Example: validate jwt token c#
public static Task<IPrincipal> validateToken(string token)
{
ClaimsPrincipal principal = getPrincipal(token);
if (principal == null)
return null;
ClaimsIdentity identity = null;
try
{
identity = (ClaimsIdentity)principal.Identity;
IPrincipal Iprincipal = new ClaimsPrincipal(identity);
return Task.FromResult(Iprincipal);
}
catch (NullReferenceException)
{
return Task.FromResult<IPrincipal>(null);
}
}
private static ClaimsPrincipal getPrincipal(string token)
{
try
{
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = (JwtSecurityToken)tokenHandler.ReadToken(token);
if (jwtToken == null)
return null;
byte[] key = Encoding.ASCII.GetBytes(config.jwtSecret);
TokenValidationParameters parameters = new TokenValidationParameters()
{
ValidIssuer = config.jwtIssuer,
ValidAudience = config.jwtIssuer,
ValidateLifetime = true,
RequireExpirationTime = true,
ValidateIssuer = true,
ValidateAudience = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ClockSkew = TimeSpan.Zero
};
SecurityToken securityToken;
ClaimsPrincipal principal = tokenHandler.ValidateToken(token,
parameters, out securityToken);
return principal;
}
catch
{
return null;
}
}