You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

91 lines
3.2 KiB

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Web;
namespace JsonRx.Helper
{
/// <summary>
/// </summary>
public class JwtTokenizer
{
private string username;
private string guid;
private string customerId;
private string fcmId;
private string deviceType;
/// <summary>
/// </summary>
public JwtTokenizer(string username, string guid, string customerId, string FCMId, string deviceTpe="")
{
this.username = username;
this.guid = guid;
this.customerId = customerId;
this.fcmId = FCMId;
this.deviceType = deviceTpe;
}
/// <summary>
/// </summary>
/// <returns></returns>
public string CreateToken()
{
//Set issued at date
DateTime issuedAt = DateTime.UtcNow;
//set the time when it expires
var time = ConfigurationManager.AppSettings["TokenExpiryInMinute"].ToString();
DateTime expires = DateTime.UtcNow.AddMinutes(Convert.ToDouble(time));
//http://stackoverflow.com/questions/18223868/how-to-encrypt-jwt-security-token
var tokenHandler = new JwtSecurityTokenHandler();
IList<Claim> claims = new List<Claim>();
if (!string.IsNullOrEmpty(username))
{
claims.Add(new Claim(ClaimTypes.Name, username));
}
if (!string.IsNullOrEmpty(guid))
{
claims.Add(new Claim("Guid", guid));
}
if (!string.IsNullOrEmpty(customerId))
{
claims.Add(new Claim("CustomerNo", customerId));
}
if (!string.IsNullOrEmpty(fcmId))
{
claims.Add(new Claim("ClientFcmId", fcmId));
}
if (!string.IsNullOrEmpty(deviceType))
{
claims.Add(new Claim("DeviceType", deviceType));
}
//create a identity and add claims to the user which we want to log in
ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims);
string sec = ConfigurationManager.AppSettings["JwtSecret"].ToString();
//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: ConfigurationManager.AppSettings["JwtAudience"].ToString(), audience: ConfigurationManager.AppSettings["JwtIssuer"].ToString(),
subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
var tokenString = tokenHandler.WriteToken(token);
return tokenString;
}
}
}