예제 #1
0
        public IActionResult Authenticate([FromBody] AccountClass user)
        {
            var account = _repo.Authenticate(user.Email, user.Password);

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

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            // return basic user info (without password) and token to store client side
            return(Ok(new
            {
                Id = account.Id,
                FirstName = account.FirstName,
                LastName = account.LastName,
                Email = account.Email,
                Adress = account.Adress,
                Postalcode = account.Postalcode,
                City = account.City,
                Phonenumber = account.Phonenumber,
                Username = account.Username,
                Credit = account.Credit,
                Token = tokenString
            }));
        }