2022年10月更文挑战12-自定义springsecurity认证

94 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第12天,点击查看活动详情

自定义springsecurity认证

前文

本文内容是基于springsecurity的一种处理。在进行常规的权限认证时,默认来讲请求中传来的用户名及密码是一种明文的方式。而在某些请求中,我们需要对于用户名和密码进行加密的处理。本文内容则是对加密的一次处理。

加密方式

首先本文中采用的加密方式为非对称加密,主要的方式为先通过请求获取到加密的公钥,从而利用公钥进行数据的加密。而服务端在进行实际的数据认证前,需要额外增加一步数据的解密操作,采用我们事先保存好的私钥,也就完成了整体的认证加密过程。

代码逻辑

public class SystemLoginFilter extends AbstractAuthenticationProcessingFilter {  
  
@Override  
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {  
if (this.postOnly && !request.getMethod().equals("POST")) {  
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());  
}  
String thirdParty = obtainThirdParty(request);  
AbstractAuthenticationToken authRequest;   
String username = obtainUsername(request);  
username = (username != null) ? decryptUsername(username) : "";  
username = username.trim();  
String password = obtainPassword(request);  
password = (password != null) ? decryptPassword(password) : "";  
authRequest = new UsernamePasswordAuthenticationToken(username, password);  
// Allow subclasses to set the "details" property  
setDetails(request, authRequest);  
return this.getAuthenticationManager().authenticate(authRequest);  
}  
  
protected String obtainPassword(HttpServletRequest request) {  
return request.getParameter(this.passwordParameter);  
}  
  
protected String obtainUsername(HttpServletRequest request) {  
return request.getParameter(this.usernameParameter);  
}  
  
protected void setDetails(HttpServletRequest request,  
AbstractAuthenticationToken authRequest) {  
authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));  
}  
  
/**  
* 用户名解密  
* @param username  
* @return  
*/  
private String decryptUsername(String username){  

}  
  
/**  
* 密码解密  
* @param password  
* @return  
*/  
private String decryptPassword(String password){  

}

代码中进行了一些逻辑的省略,主要的思路是我们需要AbstractAuthenticationProcessingFilter进行继承重写,可以参考组件中已经提供过的用户名及密码的验证逻辑。而我们需要处理的是,需要在解析得到我们的用户名和密码后,不要直接进行处理,而是进行一次解密操作,得到实际的用户名和密码,在用实际的用户名以及密码进行后续的权限认证等等逻辑,也就实现了用户名密码在传递过程中的加密。如果想要用其他数据进行身份验证,也是同样的思路,对于验证是的过滤器进行自定义处理即可。

后记

  • 千古兴亡多少事?悠悠。不尽长江滚滚流。