コード例 #1
0
        public IActionResult Login(LoginViewModel login)
        {
            // Busca o usuário pelo e-mail e senha
            Usuario usuarioBuscado = repository.BuscarEmalSenha(login.Email, login.Senha);

            if (usuarioBuscado == null)
            {
                return(NotFound("E-mail ou senha inválidos"));
            }

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Email, usuarioBuscado.Email),
                new Claim(JwtRegisteredClaimNames.Jti, usuarioBuscado.Id.ToString()),
                new Claim(ClaimTypes.Role, usuarioBuscado.Acesso.ToString())
            };

            var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("WsTower-chave-autenticacao"));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: "WsTower.WebApi",                // emissor do token
                audience: "WsTower.WebApi",              // destinatário do token
                claims: claims,
                expires: DateTime.Now.AddHours(2),
                signingCredentials: creds
                );

            return(Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token)
            }));
        }