Implement JWT Authentication

I am looking for the easiest way to implement JNON Web Token authentication with IdentityModel.Tokens.Jwt. Here is the link to the package itself:

JSON Web Token Handler For Microsoft.Net Framework 4.5 4.0.1

+1
source share
1 answer

This is what worked for me:

var securityKey = new InMemorySymmetricSecurityKey(Encoding.Default.GetBytes("MySecretKey"));
var header = new JwtHeader(new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest));
var payload = new JwtPayload();

var claims = new List<Claim>
{
    new Claim(ClaimTypes.Email, "jdoe@gmail.com"),
    ...
};

payload.AddClaims(claims);

// if you need something more complex than string/string data
payload.Add("tags", new List<string> { "admin", "user" });

var token = new JwtSecurityToken(header, payload);
var tokenString = securityTokenHandler.WriteToken(token);
0
source

All Articles