任何应用考虑到安全,绝不能明文的方式保存密码。密码应该通过哈希算法进行加密。 有很多标准的算法比如SHA或者MD5,结合salt(盐)是一个不错的选择。 Spring Security 提供了BCryptPasswordEncoder类,实现Spring的PasswordEncoder接口使用BCrypt强哈希方法来加密密码。
BCrypt每次加密后的密码,我管理员自己看数据库都没有办法获得,因为它的加密是不可逆的,而且每次加密后密码都是随机的非常安全
我们使用过程通常需要导入spring security来提供这个加盐算法
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
另外spring security默认提供一个拦截器会拦截我们的请求,而我们使用只是利用加盐算法的话那么需要修改,我们可以用如下方法做一个配置类改变默认的拦截
package com.tensquare.user.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* 安全配置类
*/
@Configuration /*让系统知道这是一个配置类*/
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
//authorizeRequests所有security全注解配置实现的开端,表示开始说明需要的权限。
//需要的权限分两部分,第一部分是拦截的路径,第二部分访问该路径需要的权限。
//antMlatchers表示拦截什么路径,permitA1任何权限都可以访问,直接放行所有。
//anyRequest()任何的请求,authenticated认证后才能访问
//.and().csrf().disable();固定写法,表示使csrf拦截失效。
http
.authorizeRequests()
.antMatchers("/**").permitAll()
.anyRequest().authenticated()
.and().csrf().disable();
}
}
这样当我们使用时候只需要注入这个加盐算法就可以使用了
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
1.我们需要在注册时候向数据库添加密码前service层离用BCrypt去加密存库 2.同样我们在做登录时候,需要先利用用户名或者手机号等唯一标识用户的数据先去查库得到整个pojp实例bean然后用BCrypt去校验前端的密码和数据存的密码是否匹配`