首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Spring Security安全框架中BCrypt强哈希加密算法使用

Spring Security安全框架中BCrypt强哈希加密算法使用

作者头像
用户9006224
发布2022-12-21 08:34:28
发布2022-12-21 08:34:28
9520
举报
文章被收录于专栏:cjz的专栏cjz的专栏

此文章不包含认证机制。 任何应用考虑到安全,绝不能明文的方式保存密码。密码应该通过某种方式进行加密。 如今已有很多标准的算法比如SHA或者MD5再结合salt(盐)使用是一个不错的选择。 废话不多说!直接开始 SpringBoot 中提供了Spring Security: BCryptPasswordEncoder类,实现Spring的PasswordEncoder接口使用BCrypt强哈希方法来加密密码。

第一步:pom导入依赖:

代码语言:javascript
复制
<dependency>
 	<groupId>org.springframework.boot</groupId>
	<artifactId>spring‐boot‐starter‐security</artifactId>
</dependency>

注意:Spring Security 它默认的是拦截所有路径,但是只是需要它的加密算法,所以我们要添加一个配置类,让所有地址可以匿名访问

Spring Security 安全配置类 *.config

代码语言:javascript
复制
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
@EnableWebSecurity
public 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

代码语言:javascript
复制
@Bean
public BCryptPasswordEncoder bcryptPasswordEncoder(){
	return new BCryptPasswordEncoder();
}

如果没有配置 BCryptPasswordEncoder 也就是没有在容器中,springboot没法管理它

第二步:使用 我用的是spring全家桶开发的,所以操作数据库是:Spring Data Jpa

代码语言:javascript
复制
@Autowired //注入BCryptPasswordEncoder
BCryptPasswordEncoder encoder;

public void deyadd(Admin admin) {
	//密码加密 encoder.encode(需要加密的密码)
	String newpassword = encoder.encode(admin.getPassword());//加密后的密码
	
	admin.setPassword(newpassword);
	adminDao.save(admin);
}

密码验证:

代码语言:javascript
复制
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;
	}
}

到此密码加密就完成了。

此文章不包含认证机制。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-11-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档