Spring Boot 整合 Spring Security,用戶登錄慢
- 2020 年 5 月 2 日
- 筆記
- spring, Spring Security, BCryptPasswordEncoder, 慢
場景
- Spring Boot + Spring Security搭建一個Web項目。
- 臨時用了inMemoryAuthentication。
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/static/**", "/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login")
.permitAll()
.defaultSuccessUrl("/index")
.and()
.logout()
.permitAll()
;
}
@Autowired
public void configureGlobal(
AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder(16))
.withUser(User.withUsername("user").password(new BCryptPasswordEncoder(16).encode("654321")).roles("USER"));
}
}
發現慢的原因是使用了BCryptPasswordEncoder加密方式,而且還new了兩次v。
解決方案
BCryptPasswordEncoder的默認加密長度是10,所有嘗試了默認的長度密碼,結果瞬間完成登錄。
可見10與16的速度差別,10應該是一個速度與安全兼顧的值。
有了長度沒有了效率也不行,所以建議使用默認長度就好。