Ejemplo n.º 1
0
        public UserTokenVM BuildUserToken(UserVM userVM)
        {
            var jwtSetting = new JwtSetting();

            _config.Bind("JwtSetting", jwtSetting);

            //UserInfo
            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim("userId", userVM.UserId.ToString()),
                new Claim("name", userVM.Name),
            };

            var expireIn = DateTime.UtcNow.AddMinutes(jwtSetting.ExpireMinutes);
            var jwtToken = GenerateJwtToken(jwtSetting, claims, expireIn);

            var tokenResponse = new UserTokenVM()
            {
                Token    = jwtToken,
                ExpireIn = new DateTimeOffset(expireIn).ToUnixTimeSeconds(),
                UserName = userVM.Name
            };

            return(tokenResponse);
        }
Ejemplo n.º 2
0
 public IActionResult Post(UserTokenVM request)
 {
     try
     {
         var result = _service.GetToken(request);
         return(Ok(result));
     }
     catch (Exception ex)
     {
         return(StatusCode(500, new { ex.Message, ex.InnerException }));
     }
 }
Ejemplo n.º 3
0
        public JWTokenVM GetToken(UserTokenVM request)
        {
            try
            {
                var model = new JWTokenVM
                {
                    Token        = GenerateJwtToken(request),
                    RefreshToken = this.GenerateRandomRefreshToken()
                };

                // Build and Save model to DB here

                return(model);
            }
            catch (Exception ex)
            {
                // Add some logs here
                throw ex;
            }
        }
Ejemplo n.º 4
0
        private string GenerateJwtToken(UserTokenVM request)
        {
            var claims = new List <Claim>
            {
                new Claim("userId", request.UserId.ToString()),
                new Claim("roleId", request.RoleId.ToString()),
                new Claim(JwtRegisteredClaimNames.Sub, request.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            var key     = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Auth:JWToken:key"]));
            var creds   = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expires = DateTime.Now.AddSeconds(double.Parse(_configuration["Auth:JWToken:expireValueSeconds"]));

            var token = new JwtSecurityToken(
                _configuration["Auth:JWToken:issuer"],
                _configuration["Auth:JWToken:issuer"],
                claims,
                expires: expires,
                signingCredentials: creds
                );

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }