Bcrypt password authentication not working

I’m trying to get my custom vue login to run validation with bycrpt (in Springboot) but the password validator is still letting every password (right or wrong) through

My controller –

    @PostMapping(path = "/login")
    public Object login(User user) throws UsernameNotFoundException {
        User existingUser = userService.findUserByEmail(user.getEmail());

        if (existingUser.getEmail() == null || existingUser.getEmail().equals("")) {
            return new UsernameNotFoundException("User not found");
        }

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = existingUser.getPassword();
        String encodedPassword = passwordEncoder.encode(password);
        boolean isPasswordMatch = passwordEncoder.matches(password, encodedPassword);
        if(isPasswordMatch) {
            return existingUser;
        }
        else {
            return "nada";
        }
    }

My axios api call –

  submit() {
    let formData = new FormData();
    formData.set("email", this.email)
    formData.set("password", this.password)
    formData.set("staySignedIn", this.staySignedIn)

    axios.post("/api/v1/login", formData,
        {headers: {'Content-Type': 'application/json'}})
        .then(res =>  {
          console.log(res) // test - REMOVE TO PREVENT CREDENTIALS FROM SHOWING IN CONSOLE RESPONSE
          if (res.status === 200) {
            this.$router.push('/');
          } else {
            console.log(res.data.code);
          }
        })
        .catch(function (err) {
          console.log(err);
          alert("Email or password is incorrect");
        })
  }

Answer

if(isPasswordMatch) {
        return existingUser;
    }
    else {
        return "nada";
    }

The root cause is your js code is just checking for the status of the response, In case of password not matching, your controller still returns status 200 with “nada” as the body. Here you should define (or use existing) and throw something like “PasswordNotMatchException” in else block and handle it accordingly.

Leave a Reply

Your email address will not be published. Required fields are marked *