Пример #1
0
        public async Task <IActionResult> Login(UserForloginDto userForLoginDto)
        {
            //throw new Exception("Computer Says No");
            var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);

            if (userFromRepo == null)
            {
                return(Unauthorized());
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                new Claim(ClaimTypes.Name, userFromRepo.UserName)
            };

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

            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(Ok(new {
                token = tokenHandler.WriteToken(token)
            }));
        }
Пример #2
0
        public async Task <IActionResult> Login(UserForloginDto userForloginDto)
        {
            var userFromRepo = await _repo.Login(userForloginDto.Username.ToLower(), userForloginDto.Password);

            if (userFromRepo == null)
            {
                return(Unauthorized());
            }

            // add identity claims
            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                new Claim(ClaimTypes.Name, userFromRepo.Username)
            };

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

            // apply signin credentials
            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);
            var user  = _mapper.Map <UserForListDto>(userFromRepo);           // _mapper.Map<Destination>(Source);

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