Example #1
0
        public string CreateToken(UserInfoViewModel userInfo, string systemTypeId, int clientNo, out DateTime invalidDateTime)
        {
            //Set issued at date
            DateTime issuedAt = DateTime.UtcNow;
            //set the time when it expires
            DateTime expires = issuedAt.AddHours(ConfigHelper.ValueInt("passwordExpire"));

            // 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
            var claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim(LotteryClaimTypes.UserName, userInfo.UserName),
                new Claim(LotteryClaimTypes.UserId, userInfo.Id),
                new Claim(LotteryClaimTypes.Email, userInfo.Email),
                new Claim(LotteryClaimTypes.Phone, userInfo.Phone),
                new Claim(LotteryClaimTypes.SystemType, systemTypeId),
                new Claim(LotteryClaimTypes.MemberRank, _memberAppService.ConcludeUserMemRank(userInfo.Id, systemTypeId)),
                new Claim(LotteryClaimTypes.ClientNo, clientNo.ToString()),
            });

            var securityKey        = new SymmetricSecurityKey(Encoding.Default.GetBytes(LotteryConstants.JwtSecurityKey));
            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

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

            invalidDateTime = DateTime.Parse(expires.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"));
            return(tokenString);
        }