Spring Security学习(三)——密码加密

前言

上一篇文章我们实现了从数据库读取用户名密码到Spring Security中,并验证登录成功。不过密码的形式有点奇怪,这篇文章我们研究一下密码加密和比对的问题。

Spring Security的密码加密和比对

密码编码器的使用

Spring Security中的密码编码器主要作用就是为密码加密和进行比对。比如当我们的web应用注册新用户,或者用户修改密码的时候,我们需要使用密码编码器把密码加密后再写入数据库。当用户登录时,输入的密码要和后台已加密的密码进行比对时,密码编码器提供比对的功能,判断两个密码是否匹配。

Spring Security为我们准备了多种密码编码器,我们可以尝试一下:

public static void main(String[] args) {
	BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(10);
	System.out.println(encoder.encode("123"));
}

运行输出,可以看到BCryptPasswordEncoder编码器对“123”进行加密,而且每次输出的结果是不一样的:

除了BCryptPasswordEncoder之外,Spring Security还提供了其他几种密码编码器,使用大同小异。

我们可以尝试进行密码的比对:

public static void main(String[] args) {
	BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(10);
	System.out.println(encoder.matches("123", encoder.encode("123")));
}

这段输出结果为true,代表匹配成功。

 

默认的密码编码器

回到我们上一篇文章的问题。为什么我们之前数据库存储的密码,要在前面加上{noop}?因为Spring Security使用的默认的密码编码器是DelegatingPasswordEncoder,它是通过策略模式选择密码比对时使用哪个密码编码器。比如密码前缀是{noop},则会使用NoOpPasswordEncoder进行比对。如果是{bcrypt}前缀,则使用BCryptPasswordEncoder。我们可以测试一下效果:

public static void main(String[] args) {
	PasswordEncoder passwordEncoder =
			PasswordEncoderFactories.createDelegatingPasswordEncoder();
	
	BCryptPasswordEncoder BCryptEncoder = new BCryptPasswordEncoder();
	Pbkdf2PasswordEncoder PbkdEncoder = new Pbkdf2PasswordEncoder();
	
	System.out.println(passwordEncoder.matches("123", "{noop}123"));
	System.out.println(passwordEncoder.matches("123", "{bcrypt}"+BCryptEncoder.encode("123")));
	System.out.println(passwordEncoder.matches("123", "{pbkdf2}"+PbkdEncoder.encode("123")));
}

运行正常的话,这里应该输出三个true。密码前面加了前缀是为了DelegatingPasswordEncoder解密使用的。同样道理,如果用DelegatingPasswordEncoder进行加密,则密码的前面会加上前缀。

为Spring Security配置密码编码器

通常我们存储密码不需要加上加密的前缀,我们只需要指定Spring Security使用哪个密码编码器就好了,在项目中增加配置类:

package com.sadoshi.springsecurity.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class WebSecurityConfig {

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}
}

这里指定使用BCryptPasswordEncoder。之后我们把前面使用BCryptPasswordEncoder加密的字符串替换调目前数据库sys_user里面的密码,然后重新启动程序,并进行登录,输入密码"123",就可以成功登陆。这样我们就不需要在密码前面加上前缀了。

小结

本文介绍了Spring Security的密码编码器,解释了上一篇文章密码前缀的问题,并且在项目中配置了默认的密码编码器。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值