Friday, January 12, 2018

JWT Sample Code

Json Web Token.

Looks like Json Web Tokens or simply JWT is having a lot of popularity that Microsoft released a library to encrypt and decrypt those tokens.

In order to generate a JWT token you should install this nuget package

System.IdentityModel.Tokens.Jwt

Then you can generate tokens that contain information like CompanyId, UserName or even password as follows

        private  string Secret = "db3OIsj+BXE9NZDy0t8W3TcNekrF+2d/1sFnWG4HnV8TZY30iTOdtVWJG8abWvB1GlOgJuQZdcF2Luqm/hccMw==";

        public  string GenerateToken()
        {
            // var hmac = new HMACSHA256();
            //Secret = Convert.ToBase64String(hmac.Key);

            var sKey = Convert.FromBase64String(Secret);
            var tHandler = new JwtSecurityTokenHandler();

            var tDesc = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim("companycode", "companycode"),
                    new Claim("username", "username"),
                    new Claim("password", "password"),
                    new Claim("companyid", "25"),
                }),

                Expires = DateTime.UtcNow.AddMinutes(45),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(sKey),SecurityAlgorithms.HmacSha256Signature),
                Issuer = "HajOnSoft.com"
            };

            var stoken = tHandler.CreateToken(tDesc);
            return  tHandler.WriteToken(stoken);
        }

In the generate token method, you can add claims to pass parameters as you please.


To get a specific value from the token you can call a method like this

        public  int GetCompanyId(string token)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken;

                if (jwtToken == null)
                    return -1;

                var symmetricKey = Convert.FromBase64String(Secret);

                var validationParameters = new TokenValidationParameters()
                {
                    RequireExpirationTime = true,
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    IssuerSigningKey = new SymmetricSecurityKey(symmetricKey)
                };

                SecurityToken securityToken;
                var principal = tokenHandler.ValidateToken(token, validationParameters, out securityToken);
                var myClaim = jwtToken.Claims.FirstOrDefault(x => x.Type == "companyid");
                if (myClaim != null)
                    return int.Parse(myClaim.Value);
                else
                {
                    return -1;
                }
            }

            catch (Exception ex)
            {
                return -1;
            }
        }


for more information visit
http://techcerberus.blogspot.com/2017/03/jwt-in-aspnet-web-api-and-mvc.html