SpringSecurity入门《之密码加密》

密码加密

SpringSecurity自定义加密和密码比对:

  • 实现PasswordEncoder接口:
package org.springframework.security.crypto.password;

public interface PasswordEncoder {
     
    // 密码加密的方法
    String encode(CharSequence var1);

    // 密码比对的方法
    boolean matches(CharSequence var1, String var2);
}
  • 在SpringSecurity配置类中使用加密接口:
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
     

   // 给登录的用户授权【从数据库中获取数据】,并给密码加密
   builder.userDetailsService(userDetailsService).passwordEncoder(getBCryptPasswordEncoder());

}

盐值加密:

  • 直接使用BCryptPasswordEncoder类作为加密类就是带盐值的加密:
@Configuration
@EnableWebSecurity
// 启用全局[方法权限控制]功能,并设置prePostEnabled为true。保证@PreAuthority/@PostAuthority/@PreFilter/@PostFilter生效
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {
     

	@Bean
	public BCryptPasswordEncoder getBCryptPasswordEncoder() {
     
	    return new BCryptPasswordEncoder();
	}
	
	@Override
	protected void configure(AuthenticationManagerBuilder builder) throws Exception {
     
	
	    // 给登录的用户授权【从数据库中获取数据】,并给密码加密
	    builder.userDetailsService(userDetailsService).passwordEncoder(getBCryptPasswordEncoder());
	
	}
	
}

你可能感兴趣的:(java,spring,后端,spring,boot)