2017-06-18 233 views
0

我有springboot其他代碼註冊一些用戶。我使用bycrpt編碼器對它進行編碼。的代碼是這樣的下面春季開機密碼Bcrypt

@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休息

+0

你的代碼沒問題。調試代碼來查找問題。打印或調試編碼和存儲的密碼前匹配 – Zico

回答

2

BCryptPasswordEncoder的encode()方法返回一個salted散列。這意味着使用相同參數調用此方法將而不是返回相同的值。

因此是matches()方法。用它來驗證密碼。

您還應該使用BCryptPasswordEncoder作爲bean,以便您可以自動裝入它。

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

我遵循您的建議。它的工作。謝啦 :) – dedypuji