Andrei
Andrei

Reputation: 44550

Implement JWT authentication

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

JSON Web Token Handler For the Microsoft .Net Framework 4.5 4.0.1

Upvotes: 1

Views: 1411

Answers (1)

Andrei
Andrei

Reputation: 44550

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, "[email protected]"),
    ...
};

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);

Upvotes: 1

Related Questions