Пример #1
0
        public async Task <IActionResult> Login(AdminForLoginDto adminForLoginDto)
        {
            if (adminForLoginDto.Username == null || adminForLoginDto.Password == null)
            {
                return(BadRequest("Please login username and password!"));
            }
            var adminFromRepo = await _repo.Login(adminForLoginDto.Username.ToLower(), adminForLoginDto.Password);

            if (adminFromRepo == null)
            {
                return(BadRequest("Wrong username or passwords!"));
            }

            var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier, adminFromRepo.Id.ToString()),
                new Claim(ClaimTypes.Surname, adminFromRepo.Name),
                new Claim(ClaimTypes.Name, adminFromRepo.AccountType)
            };

            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(3),
                SigningCredentials = creds
            };
            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptor);

            return(Ok(new
            {
                token = tokenHandler.WriteToken(token),
            }));
        }
Пример #2
0
        public async Task <ActionResult> Login([FromBody] AdminForLoginDto adminForLoginDto)
        {
            var admin = await _adminAuthRepository.Login(adminForLoginDto.Username, adminForLoginDto.Password);

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

            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(_configuration.GetSection("AppSettings:Token").Value);


            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.NameIdentifier, admin.Id.ToString()),
                    new Claim(ClaimTypes.Name, admin.Username)
                }),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
            };



            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return(Ok(tokenString));
        }