Exemplo n.º 1
0
        public IActionResult Login([FromBody] LoginModel user)
        {
            if (user == null)
            {
                return(BadRequest("Invalid client request"));
            }

            // System.Threading.Thread.Sleep(5000);

            var _user = contextUsers.Users.Find(user.UserName);

            if (user.UserName == "admin")
            {
                if (user.Password == "admin$123")
                {
                    _user = new User {
                        Username = "******", Password = "******"
                    };
                }
                else
                {
                    return(Unauthorized());
                }
            }


            if (_user == null)
            {
                return(NotFound());
            }

            if (user.Password == _user.Password)
            {
                var secretKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"]));
                var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                List <Claim> claims = new List <Claim>();
                claims.Add(new Claim(JwtRegisteredClaimNames.Sub, user.UserName));

                var tokeOptions = new JwtSecurityToken(
                    issuer: configuration["Jwt:Issuer"],
                    audience: configuration["Jwt:Issuer"],
                    claims: claims,
                    expires: DateTime.Now.AddHours(10),
                    signingCredentials: signinCredentials
                    );

                var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);


                _user.LastLogon = DateTime.Now;

                contextUsers.SaveChanges();

                return(Ok(new { Token = tokenString }));
            }
            else
            {
                return(Unauthorized());
            }
        }