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

此文章不包含认证机制。
任何应用考虑到安全,绝不能明文的方式保存密码。密码应该通过某种方式进行加密。
如今已有很多标准的算法比如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
@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

@Bean
public BCryptPasswordEncoder bcryptPasswordEncoder(){
    return new BCryptPasswordEncoder();
}

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

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

@Autowired //注入BCryptPasswordEncoder
BCryptPasswordEncoder encoder;

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

密码验证:

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;
    }
}

到此密码加密就完成了。

此文章不包含认证机制。
————————————————
版权声明:本文为CSDN博主「常家壮」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_44257023/article/details/103008530

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值