Skip to content

Instantly share code, notes, and snippets.

@pmhsfelix
Created November 26, 2012 23:33
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save pmhsfelix/4151369 to your computer and use it in GitHub Desktop.
Save pmhsfelix/4151369 to your computer and use it in GitHub Desktop.
Generating and validating JWT tokens using JWTSecurityTokenHandler
[Fact]
public void First()
{
var tokenHandler = new JWTSecurityTokenHandler();
var symmetricKey = GetRandomBytes(256/8);
var now = DateTime.UtcNow;
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, "Pedro"),
new Claim(ClaimTypes.Role, "Author"),
}),
TokenIssuerName = "self",
AppliesToAddress = "http://www.example.com",
Lifetime = new Lifetime(now, now.AddMinutes(2)),
SigningCredentials = new SigningCredentials(
new InMemorySymmetricSecurityKey(symmetricKey),
"http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
"http://www.w3.org/2001/04/xmlenc#sha256"),
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
Console.WriteLine(tokenString);
var validationParameters = new TokenValidationParameters()
{
AllowedAudience = "http://www.example.com",
SigningToken = new BinarySecretSecurityToken(symmetricKey),
ValidIssuer = "self"
};
var principal = tokenHandler.ValidateToken(tokenString, validationParameters);
Assert.True(principal.Identities.First().Claims
.Any(c => c.Type == ClaimTypes.Name && c.Value == "Pedro"));
Assert.True(principal.Identities.First().Claims
.Any(c => c.Type == ClaimTypes.Role && c.Value == "Author"));
}
}
@paulbradyping
Copy link

why arent you at your post tk421 come in please....
Ha...

Thanks for this.. Has been helpful in getting me started.... some syntax.... in my build with VS studio 2017 community... Jwt... is JWT then the rest works fine..

@zaidAhmadKhanOFS
Copy link

this code is working fine for genration of JWT Token

////////---////////////////

public static string GenerateToken(string username, int expireMinutes = 20)
    {

        //Set issued at date
        DateTime issuedAt = DateTime.UtcNow;
        //set the time when it expires
        DateTime expires = DateTime.UtcNow.AddDays(7);

        //http://stackoverflow.com/questions/18223868/how-to-encrypt-jwt-security-token
        var tokenHandler = new JwtSecurityTokenHandler();

        //create a identity and add claims to the user which we want to log in
        ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
        {
            new Claim(ClaimTypes.Name, username)
        });

        const string sec = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";
        var now = DateTime.UtcNow;
        var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
        var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);


        //create the jwt
        var token =
            (JwtSecurityToken)
                tokenHandler.CreateJwtSecurityToken(issuer: "http://localhost:50191", audience: "http://localhost:50191",
                    subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
        var tokenString = tokenHandler.WriteToken(token);

        return tokenString;

    }

@385
Copy link

385 commented Oct 26, 2018

please do this: var symmetricKey = (byte[]) GetRandomBytes(256 / 8);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment