背景
我的情况是在前端请求spring security的登录接口时,对密码字段进行了rsa加密传输,导致spring security默认的账号密码身份验证器(UsernamePasswordAuthenticationToken)拿到rsa加密后的密码通过
PasswordEncoder
的matches
方法进行匹配,失败导致的bad certificate,也就是密码错误。
版本
- Spring Security:5.x
解决方法
- 添加Filter爆改ServletRequest对象,把request.getParameter("password")的值修改为私钥解密后的密码。(快速找了一下,没有找到修改方法,就没实测了,实际上是好使的)
- 增加自定义身份验证器
AuthenticationProvider
,手动校验账号密码正确与否,后续由此展开
定义一个RSA密文身份认证类
注意替换成你自己的rsa加解密工具以及验证流程
@Component
public class RsaAuthenticationProvider implements AuthenticationProvider {
@Autowired
UserDetailsService userDetailsService;
@Autowired
RSA rsa;
/**认证成功返回authentication对象,认证失败返回null或者抛出异常*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = (String) authentication.getCredentials();
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
String loginPassword = StrUtil.str(rsa.decrypt(password, KeyType.PrivateKey), CharsetUtil.CHARSET_UTF_8);
if (userDetails.getPassword().equals(loginPassword) == false) {
throw new AuthenticationServiceException("账号或密码错误");
}
return authentication;
}
/**
* 如果此AuthenticationProvider支持指定的Authentication对象,则返回true
*
* @param authentication
* @return
*/
@Override
public boolean supports(Class<?> authentication) {
return true;
}
}
将自定义身份认证类配置到spring security中
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebServerSecurityConfig extends WebSecurityConfigurerAdapter {
/**其余配置省略*/
@Autowired
RsaAuthenticationProvider rsaAuthenticationProvider;
@Override
protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.authenticationProvider(rsaAuthenticationProvider)
;
}
}
- 参考资料:https://blog.csdn.net/yaomingyang/article/details/98785488
标题:Spring seucity增加RSA加密传输后出现bad certificate
链接:https://www.aqwdzy.com/content/101
版权:通天技术网(www.aqwdzy.com)所分享发布内容,部分为网络转载,如有侵权请立即联系方式,我们第一时间删除并致歉!
热烈庆祝通天技术网开业大吉
@通天技术网 热烈庆祝通天技术网开业大吉
热烈庆祝通天技术网开业大吉
@通天技术网 热烈庆祝通天技术网开业大吉