コード例 #1
0
        public IActionResult Authenticate([FromBody] AuthenticateModel sellerDto)
        {
            var seller = _sellerService.Authenticate(sellerDto.Username.ToLower(), sellerDto.Password);

            if (seller == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            // generate token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_config.GetSection("AppSettings:Token").Value);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.NameIdentifier, seller.Id.ToString()),
                    new Claim(ClaimTypes.Name, seller.userName)
                }),
                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 { seller.Id, tokenString }));
        }