Exemple #1
0
    /// <summary>
    /// Check if the user loging credentials are valid, return the user if they are and null otherwise.
    /// </summary>
    /// <param name="name"></param>
    /// <param name="plainPassword">Password that is not hashed</param>
    /// <returns></returns>
    public User Login(String name, String plainPassword)
    {
        User user = GetUser(name);

        if (user == null)
        {
            return(null);
        }

        PasswordHasher             hasher = new PasswordHasher();
        PasswordVerificationResult result = hasher.VerifyHashedPassword(user.passwordHash, plainPassword);

        if (result.Equals(PasswordVerificationResult.Success))
        {
            return(user);
        }
        else if (result.Equals(PasswordVerificationResult.SuccessRehashNeeded))
        {
            user.setPasswordHash(hasher.HashPassword(plainPassword), false);
            UpdateUser(user);
            return(user);
        }
        else
        {
            // Failed
            return(null);
        }
    }
        private bool VerifyPassword(Account contextEntity)
        {
            PasswordHasher <Account>   hasher = new PasswordHasher <Account>();
            PasswordVerificationResult result = hasher.VerifyHashedPassword(contextEntity, contextEntity.Password, _account.Password);

            return(result.Equals(PasswordVerificationResult.Success));
        }
        public async Task <SignInResponse> LoginUserAsync(LoginDTO loginDTO)
        {
            var user = await _userManager.FindByEmailAsync(loginDTO.Email);

            var response = new SignInResponse();

            if (user is null)
            {
                response.ErrorMessage = _configuration["ErrorMessages:UserExistError"];
                return(response);
            }

            PasswordVerificationResult passResult = _userManager.PasswordHasher.VerifyHashedPassword(user, user.PasswordHash, loginDTO.Password);

            if (passResult.Equals(PasswordVerificationResult.Failed))
            {
                response.ErrorMessage = _configuration["ErrorMessages:InvalidPassError"];
                return(response);
            }

            var signInResult = await _signInManager.PasswordSignInAsync(user.Email, loginDTO.Password, false, false);

            if (!signInResult.Succeeded)
            {
                response.ErrorMessage = _configuration["ErrorMessages:FailedLoginError"];
                return(response);
            }

            response.IsSuccesful = true;
            return(response);
        }
Exemple #4
0
        public string GenerateJwtToken(LoginUserRequest loginData)
        {
            IUser user = _readOnlyRepository.GetUserByEmail(loginData.Email);

            if (user is null)
            {
                throw new NotFoundException("Bad Reque");
            }

            PasswordVerificationResult result = _passwordHasher.VerifyHashedPassword(user, user.Password, loginData.Password);

            if (result.Equals(PasswordVerificationResult.Failed))
            {
                throw new NotFoundException("Incorrect email or password.");
            }

            List <Claim> claims = new()
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, $"{user.Name} {user.Surname}"),
                new Claim(ClaimTypes.Role, user.RoleName),
                //new Claim("DateOfBirth", user.DateOfBirth.Value.ToString("yyyy-MM-dd")),
                new Claim("Nationality", user.CountryIso2)
            };

            var key          = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_authSettings.JwtKey));
            var cred         = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expires      = DateTime.Now.AddDays(_authSettings.JwtExpiredDays);
            var token        = new JwtSecurityToken(_authSettings.JwtIssuer, _authSettings.JwtIssuer, claims, expires: expires, signingCredentials: cred);
            var tokenHandler = new JwtSecurityTokenHandler();

            return(tokenHandler.WriteToken(token));
        }
    }
        public bool ValidaUsuario(UsuarioLogin login)
        {
            Usuario retorno = null;

            retorno = _repositorio.FindByEmail(login.email).FirstOrDefault();
            if (retorno == null)
            {
                throw new ExceptionExists("Invalid e-mail or password");
            }

            string passHashed = _passwordHasher.HashPassword(retorno, login.password);

            PasswordVerificationResult logar = _passwordHasher.VerifyHashedPassword(retorno, retorno.password, login.password);


            if (logar.Equals(PasswordVerificationResult.Failed))
            {
                Console.WriteLine("Senha não bate");
                throw new ExceptionExists("Invalid e-mail or password");
            }
            return(true);
        }
Exemple #6
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            model.Password = model.Password.ToLower();
            FormsAuthentication.SignOut();
            AuthenticationManager.SignOut();
            if (!ModelState.IsValid)
            {
                return(View(model));
            }


            //比對驗證碼
            if (System.Configuration.ConfigurationManager.AppSettings["VerificationCode"] != null)
            {
                var VerificationText = System.Configuration.ConfigurationManager.AppSettings["VerificationCode"];
                var VerificationCode = Session[VerificationText].ToString();
                if (string.IsNullOrEmpty(model.VerificationCode) || VerificationCode.ToUpper() != model.VerificationCode.ToUpper())
                {
                    ModelState.AddModelError("", "無效的驗證碼");
                    return(View());
                }
            }

            //使用者是否存在
            var user = await UserManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                ModelState.AddModelError("", "無效的帳號密碼");
                return(View(model));
            }

            //密碼檢查
            PasswordVerificationResult status = UserManager.PasswordHasher.VerifyHashedPassword(user.PasswordHash, model.Password);

            if (user == null || !status.Equals(PasswordVerificationResult.Success))
            {
                ModelState.AddModelError("", "無效的帳號密碼");
                return(View(model));
            }

            if (!user.EmailConfirmed)
            {
                //return RedirectToAction("SendCode");
                ModelState.AddModelError("", "未完成信箱驗證");
                return(View(model));
            }



            if (user != null && status.Equals(PasswordVerificationResult.Success))
            {
                await SignInAsync(user, model.RememberMe);

                CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();

                serializeModel.ID       = user.Id;
                serializeModel.Name     = user.UserName;
                serializeModel.Email    = user.Email;
                serializeModel.UserCode = user.UserCode;
                serializeModel.UserType = user.UserType;
                var UserRoles = (from rr in RoleManager.Roles.ToList()
                                 join r1 in user.Roles on rr.Id equals r1.RoleId
                                 select rr.Name).ToList();

                //var r = (from uRoles in user.Roles
                //        join rr in RoleManager.Roles.ToList() on uRoles.RoleId == rr.RoleId).to


                serializeModel.roles = string.Join(",", UserRoles);
                // serializeModel.roles = "Admin";
                var ExpireDateTime = DateTime.Now.AddDays(3);
                if (model.RememberMe)
                {
                    ExpireDateTime = DateTime.Now.AddDays(15);
                }

                string userData = JsonConvert.SerializeObject(serializeModel);
                FormsAuthenticationTicket authTicket = null;
                authTicket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddDays(15), false, userData);

                string     encTicket = FormsAuthentication.Encrypt(authTicket);
                HttpCookie faCookie  = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
                {
                    Expires = authTicket.Expiration, Path = "/"
                };
                System.Web.HttpContext.Current.Response.Cookies.Add(faCookie);


                _db.SystemLog.Add(new SystemLog
                {
                    Created        = DateTime.Now,
                    Creator        = model.Email,
                    IP             = IPaddress,
                    LogCode        = "Time",
                    LogType        = "SignIn",
                    LogDescription = "登入時間",
                    LogValue       = DateTime.Now.ToString()
                });
                _db.SaveChanges();

                return(RedirectToLocal(returnUrl));
            }


            return(View(model));
        }
Exemple #7
0
        public static void Main(string[] args)
        {
            //-------------------Hash Passord--------------------------
            string salt     = "9";
            string password = "******";
            IPasswordHasher <MyUser> _hasher = new PasswordHasher <MyUser>();
            var hashedPassword = _hasher.HashPassword(new MyUser()
            {
                Username = "******"
            }, password + salt);

            PasswordVerificationResult status = _hasher.VerifyHashedPassword(new MyUser()
            {
                Username = "******"
            }, hashedPassword, password + salt);

            if (status.Equals(PasswordVerificationResult.Success))
            {
                Console.WriteLine("Hurrrrrrrrah");
            }

            Console.ReadKey();



            //--------------------------------------------------


            //string UserName = "******";
            //string callbackUrl = "http://calbackurl.com";
            //string loginUrl = "http://loginurl.com";
            //string htmlmessage = String.Format("<b>Hi {0}.</b><br/><br/>Please click<b> <a href='{1}'> here </a></b>" +
            //                      "to reset your password. <br/><br/>The link is valid for 24 hours.<br/><br/><br/><b>If you did NOT request a new password," +
            //                      "do not click on the link. </b><br/><br/>You can access the Remote Caretaking system <a href='{2}'> here. </a>",
            //                      UserName, callbackUrl, loginUrl);

            //string htmlMessage2 = String.Format("<b>Hi {0}.</b><br/><br/>You have been invited to the BitzerIoc system." +
            //                          "<br/><br/>User name = {0} <br/><br/>" +
            //                          "To activate your account and create a password please <a href='{1}' > click here. </a>" +
            //                          "<br/><br/>You can access the Remote Caretaking system <a href='{2}'> here. </a> <br/><br/>Best regards",
            //                          UserName, callbackUrl, loginUrl);
            //Console.WriteLine(htmlMessage2);

            //-----------------------------------------------------------------------------//
            //string queryString = "http://msn.com?p1=6&p2=7&p3=8";
            //if (queryString.Contains("?"))
            //{
            //    queryString = queryString.Remove(0, queryString.IndexOf('?') + 1);
            //}
            //Dictionary<string, string> queryParameters = new Dictionary<string, string>();
            //string[] querySegments = queryString.Split('&');
            //foreach (string segment in querySegments)
            //{
            //    string[] parts = segment.Split('=');
            //    if (parts.Length > 0)
            //    {
            //        string key = parts[0].Trim(new char[] { '?', ' ' });
            //        string val = parts[1].Trim();
            //        queryParameters.Add(key, val);

            //    }
            //}

            //------------------------- Replace a specific TExt------------------
            //string returnUrl = "redirect_uri=http://loclahost:5000:/signin-oidc";
            //string redirectUri = null;
            //Dictionary<string, string> queryStringCollection = GenericHelper.ParseQueryString(returnUrl);
            //queryStringCollection.TryGetValue("redirect_uri", out redirectUri);

            //string removeString = "signin-oidc";
            //int index = redirectUri.IndexOf(removeString);
            //string cleanPath = (index < 0)
            //    ? redirectUri
            //    : redirectUri.Remove(index, removeString.Length);
            //var a = cleanPath;

            //---------------------------- Hashing --------------------------------

            //Console.Write("Enter a password: "******"7da61e6725aa27ca4f5a5ae0e73ea7dd";
            //string oldpassword = "";
            //var hash = HashSecurity.GetHash(password + salt);


            //if (HashSecurity.CompareHashText(password, oldpassword, salt))
            //    Console.WriteLine("Logged in");
            //else
            //    Console.WriteLine("Fail Login attempt");


            ////// generate a 128 - bit salt using a secure PRNG
            //// byte[] salt = HashSecurity.GetSalt(128 / 8);

            //// // derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations)
            //// string hashed = HashSecurity.Hash(password, salt, 128 / 8, 10000, KeyDerivationPrf.HMACSHA1);
            //// Console.WriteLine("Salt:" + Convert.ToBase64String(salt));
            //// Console.WriteLine($"Hashed: {hashed}");

            //Console.WriteLine(hash);

            //------------------------------------- Static Test -----------------------------------

            //ClassA.Print();
            //Console.ReadKey();
            //ClassA.Print();
            //Console.ReadKey();
            //ClassA.Print();
            //Console.ReadKey();

            //--------------------------------------------------------------------------------------
        }