Implement JWT authentication

2019-08-10 03:44发布

问题:

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

回答1:

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