bcrypt密码编码与springboot中的输入密码不匹配?

mctunoxg  于 2021-09-30  发布在  Java
关注(0)|答案(1)|浏览(419)

我正在使用springsecurity bcrypt密码编码器对我的密码进行编码这就是我保存密码的方式

public User saveUser(User newUser) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(newUser.getPassword());
        newUser.setPassword(encode);
        User user = userRepo.save(newUser);
        return user;

    }

这就是我定义bean的方式

@Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();

    }

但是,当我尝试将密码与编码的密码匹配时,我无法登录。我使用了passwordencoder.matches,但没有帮助

public Response login(String username, String password) throws Exception {
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            Response response = new Response();
            Optional<User> byuser_nameAndPassword = userRepo.getByuser_nameAndPassword(username);
            User user = byuser_nameAndPassword.get();
            String encodedPassword = passwordEncoder.encode(password);
            boolean matches = passwordEncoder.matches(encodedPassword, user.getPassword());
            if (matches){
                response.setStatus(201);
                response.setMessage("Login Succeeded");
            } else {
                response.setStatus(403);
                response.setMessage("You are not Authorized");
            }

            return response;
        }

    }

感谢您的帮助。

z3yyvxxp

z3yyvxxp1#

您正在以不正确的格式将参数传递给 boolean matches = passwordEncoder.matches(encodedPassword, user.getPassword()); 文件说:
布尔匹配​(java.lang.charsequence(密码,java.lang.string encodedpassword)
第一个参数必须是原始密码,而不是编码密码。
应该是:

boolean matches = passwordEncoder.matches(password, user.getPassword())

相关问题