此文章不包含认证机制。
任何应用考虑到安全,绝不能明文的方式保存密码。密码应该通过某种方式进行加密。
如今已有很多标准的算法比如SHA或者MD5再结合salt(盐)使用是一个不错的选择。
废话不多说!直接开始
SpringBoot 中提供了Spring Security:
BCryptPasswordEncoder类,实现Spring的PasswordEncoder接口使用BCrypt强哈希方法来加密密码。
第一步:pom导入依赖:
<dependency> <groupId>org.springframework.boot</groupId><artifactId>spring‐boot‐starter‐security</artifactId></dependency>注意:Spring Security 它默认的是拦截所有路径,但是只是需要它的加密算法,所以我们要添加一个配置类,让所有地址可以匿名访问
Spring Security 安全配置类 *.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;/** * Spring Security安全配置类 */@Configuration@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter{ @Override protected void configure(HttpSecurity http) throws Exception { /** * authorizeRequests() 是所有security全注解配置实现的开端,表示开始说明需要的权限。 * 需要的权限分两部分,第一部分是拦截的路径,第二部分访问该路径需要的权限。 * antMatchers是表示拦截什么路径,permitAll()任何权限都可以访问,就是直接放行所有。 * anyRequest()任何的请求,authenticated 认证后才能访问。 * .and().csrf().disable(); 固定写法,表示使csrf拦击失效(csrf 是网络攻击技术。有想了解自己找资料)。 */ http .authorizeRequests() .antMatchers("/**").permitAll() .anyRequest().authenticated() .and().csrf().disable(); }}在springboot 启动类中添加配置BCryptPasswordEncoder
@Beanpublic BCryptPasswordEncoder bcryptPasswordEncoder(){return new BCryptPasswordEncoder();}如果没有配置 BCryptPasswordEncoder 也就是没有在容器中,springboot没法管理它
第二步:使用
我用的是spring全家桶开发的,所以操作数据库是:Spring Data Jpa
密码验证:
public Addmin deyPassword(String loginname, String password){//查询数据库中的密码Addmin addmin = adminDao.findByLoginname(loginname);//密码验证 encoder.matches(输入的密码,数据库中的密码)if( addmin!=null && encoder.matches(password,admin.getPassword())){return addmin;{else{return null;}}到此密码加密就完成了。
此文章不包含认证机制。