SpringBoot使用BCryptPasswordEncoder进行密码加密

为了数据库安全,现在一般不在数据库,前端将密码传入后端进行处理,后端对密码进行加密,然后再储存到数据库中,SpringBoot框架一般使用的是BCryptPasswordEncoder来进行操作。

1.加入依赖

        <!--        securityr认证-->
        <dependency>
	        <groupId>org.springframework.boot</groupId>
	        <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

2.加密

        User newUser = new User();
        BeanUtils.copyProperties(user,newUser);
        newUser.setPassword(encoder.encode(user.getPassword()));
        this.save(newUser);

3.匹配

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = this.getOne(queryWrapper);
        if(user == null){
            return 0;
        }
        final boolean matches = encoder.matches(password, user.getPassword());
        if(matches){
            return 1;
        }
        return 0;

4.在启动类下添加一方法

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

5.在config包下新建SecurityConfig.java文件


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/**").permitAll()
                .and()
                .csrf().disable();//相当于<security:scrf enabled=false/>标签
    }


}

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值