コード例 #1
0
        public SecurityToken CreateToken(UserForTokenDto userForToken,
                                         SymmetricSecurityKey key, string userRole, string city)
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userForToken.id.ToString()),
                new Claim(ClaimTypes.Name, userForToken.Username),
                new Claim(ClaimTypes.StateOrProvince, city)
            };

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(token);
        }
コード例 #2
0
        public IActionResult CreateToken(UserForTokenDto userForToken)
        {
            if (int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value) != userForToken.id)
            {
                return(Unauthorized());
            }

            var key = new SymmetricSecurityKey(Encoding.UTF8
                                               .GetBytes(_config.GetSection("AppSettings:Token").Value));

            string userRole = User.FindFirst(ClaimTypes.Role).Value;
            string city     = User.FindFirst(ClaimTypes.StateOrProvince).Value;

            var token = _repo.CreateToken(userForToken, key, userRole, city);

            var tokenHandler = new JwtSecurityTokenHandler();

            return(Ok(new {
                token = tokenHandler.WriteToken(token)
            }));
        }