Exemplo n.º 1
0
        public TokenUserDTO CreateJwt(Member member)
        {
            string Key         = _configuration["Token:SecretKey"];
            var    securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Key));

            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            string userRole = "Member";

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Role, userRole),
                new Claim("UserId", member.MailId.ToString())
            };

            var token = new JwtSecurityToken(
                issuer: _configuration["Token:Issuer"],
                audience: _configuration["Token:Audience"],
                claims: claims,
                expires: DateTime.Now.AddMinutes(15),
                signingCredentials: credentials);

            TokenUserDTO tokenUser = new TokenUserDTO();

            tokenUser.MemberId = member.MemberId;
            tokenUser.Token    = new JwtSecurityTokenHandler().WriteToken(token);

            return(tokenUser);
        }
Exemplo n.º 2
0
        private async void OnLoginButtonClick()
        {
            CanLoginFlag = false;
            CredentialsUserDTO credentials = new CredentialsUserDTO()
            {
                username = Username, password = Password, grant_type = "password"
            };

            TokenUserDTO token = await UserService.LoginUser(credentials);

            if (token != null && token.success)
            {
                ActiveUser.Instance.LoggedUser = new TokenUser
                {
                    Username = token.userName,
                    Token    = "Bearer " + token.access_token
                };
                //ShowMessageBox(null, "Login successful");
                LoginButtonAction?.Invoke();
            }
            else
            {
                ShowMessageBox(null, "Login failed");
            }
            CanLoginFlag = true;
        }
        public async Task <ActionResult> Login(MemberLoginDTO member)
        {
            HttpClient client = new HttpClient();
            string     uri    = "http://localhost:7047/api/Authorization/Login";

            StringContent content    = new StringContent(JsonConvert.SerializeObject(member), Encoding.UTF8, "application/json");
            var           myResponse = await client.PostAsync(uri, content);

            if (myResponse.StatusCode == HttpStatusCode.OK)
            {
                TokenUserDTO tokenUser = myResponse.Content.ReadAsAsync <TokenUserDTO>().Result;
                HttpContext.Session.SetString("JWTToken", tokenUser.Token);
                HttpContext.Session.SetInt32("MemberId", tokenUser.MemberId);

                //HttpClient client1 = new HttpClient();
                //client1.BaseAddress = new Uri("http://localhost:53504");
                //var token = HttpContext.Session.GetString("JWTToken");
                //StringContent content1 = new StringContent(JsonConvert.SerializeObject(tokenUser.Token), Encoding.UTF8, "application/json");
                //client1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                //HttpResponseMessage response = client1.PostAsync("/api/Subscription/setToken", content1).Result;

                return(RedirectToAction("Index", "Member"));
            }
            else
            {
                ViewBag.Message = "Invalid Credentials.";
                return(View());
            }
        }
Exemplo n.º 4
0
        public ActionResult <TokenUserDTO> Login(UserDTO userDTO)
        {
            var myUser = users.SingleOrDefault(usr => usr.Username == userDTO.Username);

            if (myUser != null)
            {
                using var hmac = new HMACSHA512(myUser.PasswordSalt);
                var checkPasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(userDTO.Password));
                for (int i = 0; i < checkPasswordHash.Length; i++)
                {
                    if (checkPasswordHash[i] != myUser.PasswordHash[i])
                    {
                        return(Unauthorized("Invalid Password"));
                    }
                }
                //return myUser;

                var tokenUser = new TokenUserDTO
                {
                    Username = myUser.Username,
                    Token    = _tokenGenerate.CreateToken(myUser)
                };
                return(tokenUser);
            }
            else
            {
                return(Unauthorized("Username does not exist"));
            }
        }
        public ActionResult Login([FromBody] MemberLoginDTO member)
        {
            _log4net.Info("HttpPost request : " + nameof(Login));
            if (member == null)
            {
                return(BadRequest("Member details cannot be empty"));
            }

            try
            {
                Member AuthenticatedUser = _service.AuthenticateUser(member);
                if (AuthenticatedUser != null)
                {
                    TokenUserDTO token = _service.CreateJwt(AuthenticatedUser);
                    return(Ok(token));
                }
                else
                {
                    return(BadRequest("Invalid Credentials!!!"));
                }
            }
            catch (Exception e)
            {
                _log4net.Error("Exception Occured : " + e.Message + " from " + nameof(Login));
                return(BadRequest("Exception Occured"));
            }
        }
Exemplo n.º 6
0
        public async Task <TokenUserDTO> GetTokenLogin([FromBody] UsuarioLoginDTO user)
        {
            try
            {
                /* FAZ O LOGIN */
                var userExists = await _signInManager.PasswordSignInAsync(user.Email, user.Password, true, false);

                TokenUserDTO token = null;
                if (userExists.Succeeded)
                {
                    /* Ele existe... logo loga... */
                    Usuario usuario = await _rep.GetUserByEmail(user.Email);

                    var tokenGerado = GetAuth.GenerateToken(usuario);
                    token = new TokenUserDTO()
                    {
                        TokenUrsao = tokenGerado,
                    };
                    return(token);
                }
                else
                {
                    throw new UsuarioNaoEncontradoException("usuario nao encontrado :P");
                }
            }
            catch (Exception e)
            {
                return(new TokenUserDTO()
                {
                    TokenUrsao = "Puuuxa não foi dessa vez... Mas ligue novamente para 4002-8922 q vc será atendido pelo SBT! --- SACANAGEM... KKKKK na real a msg é essa mano: Ocorreu algum erro interno na aplicação, por favor tente novamente... Erro: " + e.Message,
                });
            }
        }
 public ActionResult Login([FromBody] MemberLoginDTO member)
 {
     if (member == null)
     {
         return(BadRequest("Member details cannot be empty"));
     }
     else
     {
         Member AuthenticatedUser = _service.AuthenticateUser(member);
         if (AuthenticatedUser != null)
         {
             TokenUserDTO token = _service.CreateJwt(AuthenticatedUser);
             return(Ok(token));
         }
         else
         {
             return(BadRequest("Invalid Credentials!!!"));
         }
     }
 }
Exemplo n.º 8
0
        public static async Task <TokenUserDTO> LoginUser(CredentialsUserDTO credentialsUserDTO)
        {
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    // sending of register data
                    string encoded_url =
                        "grant_type=" + credentialsUserDTO.grant_type + "&" +
                        "username="******"&" +
                        "password="******"application/x-www-form-urlencoded");
                    var response = await client.PostAsync("http://localhost:52816/Token", byteContent);

                    // parsing response
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        var jsonString = await response.Content.ReadAsStringAsync();

                        TokenUserDTO tokenResponse = JsonConvert.DeserializeObject <TokenUserDTO>(jsonString);
                        tokenResponse.success = true;
                        return(tokenResponse);
                    }
                    else
                    {
                        return(null);
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                    return(null);
                }
            }
        }
        public async Task <TokenUserDTO> GetTokenLogin([FromBody] UsuarioLoginDTO user)
        {
            try
            {
                /* FAZ O LOGIN */
                var userExists = await _signInManager.PasswordSignInAsync(user.Email, user.Password, true, false);

                TokenUserDTO token = null;
                if (userExists.Succeeded)
                {
                    /* Ele existe... logo loga... */
                    Usuario usuario = await _rep.GetUsuarioPorEmail(new UsuarioPorEmailDTO()
                    {
                        Email = user.Email
                    });

                    var tokenGerado = GetAuth.GenerateToken(usuario);
                    token = new TokenUserDTO()
                    {
                        Token = tokenGerado,
                    };
                    return(token);
                }
                else
                {
                    throw new UsuarioNaoEncontradoException("usuario nao encontrado");
                }
            }
            catch (Exception e)
            {
                return(new TokenUserDTO()
                {
                    Token = "Ocorreu algum erro interno na aplicação, por favor tente novamente... Erro: " + e.Message,
                });
            }
        }