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"));
}
}
@sudharsanprc
Copy link

I created the console app to create JWT token. But still i am unable to login using the SSO in successful.
I have a private key . Need to know wheather i read the key in proper way and building the token.

My code 👍
using System.Configuration;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Security.Cryptography;

namespace testtoken
{
public class Program
{
///


/// Main method, which invokes sub methods to create Jwt Token.
///

public static void Main(string[] args)
{
// Create the file object to log the data.
// Log file path detailed in config file.
StreamWriter tokenFile = File.AppendText(ConfigurationManager.AppSettings.Get(("path")));
Log("Jwt Token File Log.", tokenFile);
Log("--------------------------", tokenFile);
Log("", tokenFile);
Log("Timestamp : " + DateTime.Now.ToString("yyyy-MM-dd:HH:mm:ss:fff"), tokenFile);
Log("Call a method GenerateJwtToken() to create the token object", tokenFile);

        // Create Token Handler
        var tokenobj = new GenerateJwtToken();

        // Log the data
        Log("Call a method Encode to build Token body with Name, Email and Role as parameters", tokenFile);
        Log("Name : " + ConfigurationManager.AppSettings.Get(("Name")), tokenFile);
        Log("Email : " + ConfigurationManager.AppSettings.Get(("Email")), tokenFile);
        Log("Role : " + ConfigurationManager.AppSettings.Get(("Role")), tokenFile);
        tokenFile.Close();

        // Call Encode method build , sign and create the token
        var jwtToken = tokenobj.Encode(ConfigurationManager.AppSettings.Get(("Name")), ConfigurationManager.AppSettings.Get(("Email")), ConfigurationManager.AppSettings.Get(("Role")));

        // Log the token value and other available data
        StreamWriter tokenFile2 = File.AppendText(ConfigurationManager.AppSettings.Get(("path")));
        Log("Printing Jwt Token", tokenFile2);
        Log("Token : " + jwtToken, tokenFile2);
        Log("End of Token", tokenFile2);
        Log("End of Log", tokenFile2);
        Log("--------------------------", tokenFile2);
        Log("", tokenFile2);
        tokenFile2.Close();
        Console.WriteLine("Token File available in Path :" + ConfigurationManager.AppSettings.Get(("path")));
    }

    /// <summary>
    /// GenerateJwtToken class, build and creates the Jwt Token for the received parameters
    /// </summary>
    public class GenerateJwtToken
    {
        /// <summary>
        /// Create the token handler and build the token with claims.
        /// </summary>
        /// <param name="strName">The name of the patient</param>
        /// <param name="strEmail">Patient email ID</param>
        /// <param name="strRole">Patient Role</param>
        /// <returns></returns>
        public string Encode(string strName, string strEmail, string strRole)
        {
            StreamWriter tokenFile = File.AppendText(ConfigurationManager.AppSettings.Get(("path")));
            Log("Inside the Encode() function call", tokenFile);
            Log("Create the JwtSecurityTokenHandler() object", tokenFile);
            // Create the handler
            var handler = new JwtSecurityTokenHandler();
            Log("Call to the method BuildToken(), to build the token with claims and Header", tokenFile);
            Log("The parameters are Name : " + strName + " Email :" + strEmail + " Role : " + strRole, tokenFile);
            tokenFile.Close();
            // Build the token
            var tk421 = BuildToken(strName, strEmail, strRole);
            var token = tk421;
            // Return the token to Encode method
            return handler.WriteToken(token);
        }

        /// <summary>
        /// Build the Token body with patient email, name and Role.
        /// </summary>
        /// <param name="strName">Patient name</param>
        /// <param name="strEmail">Patient Email ID</param>
        /// <param name="strRole">Role</param>
        /// <returns></returns>
        private JwtSecurityToken BuildToken(string strName, string strEmail, string strRole)
        {
            StreamWriter tokenFile = File.AppendText(ConfigurationManager.AppSettings.Get(("path")));

            Log("Build the claims for the token body", tokenFile);
            // Create the claim list with name, email and Role ( patient or Doctor )
            var claimList = new List<Claim>
            {
                new Claim(ClaimTypes.Name, strName),
                new Claim(ClaimTypes.Email, strEmail),
                new Claim(ClaimTypes.Role, strRole)
            };

            Log("Create the JwtSecurityTokenHandler Object", tokenFile);
            // Create the security handler to call    
            var handler = new JwtSecurityTokenHandler();

            Log("Get the current time stamp in UTC", tokenFile);
            // Create the UTC time stamp to provide the validity to the token
            var dtUtcNow = DateTime.UtcNow;

            Log("Timestamp " + dtUtcNow, tokenFile);
            Log("Build the symmetric key - Predefined private key", tokenFile);

           // Build the symmetric key.                
           // var symmetricKey = GetBytes((ConfigurationManager.AppSettings.Get("PrivateKey")));

            string path = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\PrivateKey.xml"));
            Log("Read the Private Key from the file Path : " + path, tokenFile);
            Log("Initializes a new instance of the RSACryptoServiceProvider class using the default key", tokenFile);

            // Create an object instance for the class RSACryptoServiceProvider
            var rsa = new RSACryptoServiceProvider();
            Log("RSA object reads the private key", tokenFile);

            // Read the private key from the XML file
            rsa.FromXmlString(System.IO.File.ReadAllText(path));
            Log("Export a blob which contains the private key info", tokenFile);

            // Export as byte, which is passed as parameter for signingCredentials.                
            var symmetricKey = rsa.ExportCspBlob(true);

            // Log the token descriptor values
            Log("Build the token Descriptor", tokenFile);
            Log("Audience : " + ConfigurationManager.AppSettings.Get("Audience"), tokenFile);
            Log("Issuer: " + ConfigurationManager.AppSettings.Get("Issuer"), tokenFile);
            Log("Expires in Minutes: " + ConfigurationManager.AppSettings.Get("TokenExpirationMinutes"), tokenFile);
            Log("SigningCredentials : HmacSha256Signature", tokenFile);

            // Build the token descriptor
            var securityTokenDescriptor = new SecurityTokenDescriptor()
            {
                Subject = new ClaimsIdentity(claimList),
                Audience = ConfigurationManager.AppSettings.Get("Audience"),
                Issuer = ConfigurationManager.AppSettings.Get("Issuer"),
                Expires = dtUtcNow.AddMinutes(double.Parse(ConfigurationManager.AppSettings.Get("TokenExpirationMinutes"))),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricKey), SecurityAlgorithms.HmacSha256Signature),
            };

            Log("Create the Jwt Token using the method CreateToken()", tokenFile);
            // Create JWT token.
            var tk421 = handler.CreateToken(securityTokenDescriptor);

            tokenFile.Close();

            // Return the token to Encode function call, which in turn return to Main function.
            return (JwtSecurityToken)tk421;

        }

        /// <summary>
        /// This method convert the received string into bytes. 
        /// </summary>
        /// <param name="str">Private key values</param>
        /// <returns></returns>
        private static byte[] GetBytes(string str)
        {
            var bytes = new byte[str.Length * sizeof(char)];
            Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }
    }

    /// <summary>
    /// Log method writes all the string messages into text file at the location given in config file
    /// </summary>
    /// <param name="logMessage">Message string</param>
    /// <param name="txWriter">File Handler</param>
    public static void Log(string logMessage, TextWriter txWriter)
    {
        txWriter.WriteLine(logMessage);
    }
}

}

@sudharsanprc
Copy link

Let me know if my approach needs to be changed.

@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