【问题标题】:Spring boot password Bcrypt春季开机密码Bcrypt
【发布时间】:2017-06-18 08:21:45
【问题描述】:

我有 springboot 休息代码来注册一些用户。我使用 bycrpt 编码器对其进行编码。下面的代码是这样的

@RequestMapping(value="/customer/new", method=RequestMethod.POST)
    public Customer newCustomer (@RequestBody Customer customer){
            customer.setPassword(new BCryptPasswordEncoder().encode(customer.getPassword()));
        return customerservice.saveCustomer(customer);
        }

所以它成功地用编码密码存储密码 像这样的东西 $2a$10$f25IxR/b7wNJBl7Zi.zEMOzpR2nDEw7IJwR3tv/BVKsKJRAtDe1Mq

所以我像下面这样制作登录休息控制器

@RequestMapping(value = "customer/login", method = RequestMethod.POST)
        public String login(@RequestBody Customer login) throws ServletException {

            String jwtToken = "";

            if (login.getUsername()== null || login.getPassword()== null) {
                throw new ServletException("Please fill in username and password");
            }

            String username = login.getUsername();
            String password = new BCryptPasswordEncoder().encode(login.getPassword());


            Customer customer = customerservice.findByusername(username);

            if (customer == null) {
                throw new ServletException("Username not found.");
            }

            String pwd = customer.getPassword();

            if (!password.equals(pwd)) {
                throw new ServletException("Invalid login. Please check your name and password.");
            }

登录休息控制器从输入中获取用户名并从用户输入中获取密码。我尝试对密码进行编码,以便它可以作为 Bcrypt 编码密码返回并匹配之前存储的密码。

但它不匹配。我可以得到相同的密码编码。如何解决? 我是新来的使用 springboot 休息

【问题讨论】:

  • 你的代码没问题。调试代码以发现问题。在匹配之前打印或调试编码和存储的密码

标签: spring-mvc spring-boot


【解决方案1】:

BCryptPasswordEncoder 的encode() 方法返回一个加盐哈希。这意味着使用相同的参数调用此方法将不会返回相同的值。

因此是matches() 方法。使用它来验证密码。

您还应该使用 BCryptPasswordEncoder 作为 bean,以便您可以自动装配它。

@Configuration
public class SomeConfigurationClass {
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(12);
    }
}

【讨论】:

    猜你喜欢
    • 2020-06-29
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多