Spring Security账户与密码验证实现过程
作者:T.Y.Bao 时间:2023-03-04 21:54:37
这里使用Spring Boot 2.7.4版本,对应Spring Security 5.7.3版本
本文样例代码地址: spring-security-oauth2.0-sample
关于Username/Password认证的基本流程和基本方法参见官网 Username/Password Authentication
Introduction
Username/Password认证主要就是Spring Security 在 HttpServletRequest中读取用户登录提交的信息的认证机制。
Spring Security提供了登录页面,是前后端不分离的形式,前后端分离时的配置需另加配置。本文基于前后端分离模式来叙述。
基本流程如下:
Username/Password认证可分为两部分:
从HttpServletRequest中获取用户登录信息
从密码存储处获取密码并比较
关于获取获取用户登录信息,Spring Security支持三种方式(基本用的都是Form表单提交,即POST方式提交):
Form
Basic
Digest
关于密码的获取和比对,关注下面几个类和接口:
UsernamePasswordAuthenticationFilter
: 过滤器,父类AbstractAuthenticationProcessingFilter
中组合了AuthenticationManager
,AuthenticationManager
的默认实现ProviderManager
中又组合了多个AuthenticationProvider
,该接口实现类,有一个DaoAuthenticationProvider
负责获取用户密码以及权限信息,DaoAuthenticationProvider
又把责任推卸给了UserDetailService
。PasswordEncoder
: 密码加密方式UserDetails
: 代表用户,包括 用户名、密码、权限等信息UserDetailsService
: 最终实际调用获取UserDetails
的接口,通常用户实现。
整个流程的UML图如下:
前后端分离模式下配置
先来看对SecurityFilterChain的配置:
@Configuration
@EnableMethodSecurity()
@RequiredArgsConstructor
public class SecurityConfig {
// 自定义成功处理,主要存储登录信息并返回jwt
private final LoginSuccessHandler loginSuccessHandler;
// 自定义失败处理,返回json格式而非默认的html
private final LoginFailureHandler loginFailureHandler;
private final CustomSessionAuthenticationStrategy customSessionAuthenticationStrategy;
...
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
// 设置登录成功后session处理, 认证成功后
// SessionAuthenticationStrategy的最早执行,详见AbstractAuthenticationProcessingFilter
// 执行顺序:
// 1. SessionAuthenticationStrategy#onAuthentication
// 2. SecurityContextHolder#setContext
// 3. SecurityContextRepository#saveContext
// 4. RememberMeServices#loginSuccess
// 5. ApplicationEventPublisher#publishEvent
// 6. AuthenticationSuccessHandler#onAuthenticationSuccess
http.sessionManagement().sessionAuthenticationStrategy(customSessionAuthenticationStrategy);
...
// 前后端不分离,可指定html返回。该项未测试
// http.formLogin().loginPage("login").loginProcessingUrl("/hello/login");
// 前后端分离下username/password登录
http.formLogin()
.usernameParameter("userId")
.passwordParameter("password")
// 前端登陆页面对这个url提交username/password即可
// 必须为Post请求,且Body格式为x-www-form-urlencoded,如果要接受application/json格式,需另加配置
.loginProcessingUrl("/hello/login")
.successHandler(loginSuccessHandler)
.failureHandler(loginFailureHandler);
// .securityContextRepository(...) // pass
...
return http.build();
}
...
}
使用Postman测试:
登录成功登陆失败
AbstractAuthenticationProcessingFilter
该类是UsernamePasswordAuthenticationFilter
和OAuth2LoginAuthenticationFilter
的父类,使用模板模式构建。
UsernamePasswordAuthenticationFilter
只负责从HttpServletRequest
中获取用户提交的用户名密码,而真正去认证、事件发布、SessionAuthenticationStrategy、AuthenticationSuccessHandler、AuthenticationFailureHandler、SecurityContextRepository、RememberMeServices这些内容均组合在AbstractAuthenticationProcessingFilter
中。
public abstract class AbstractAuthenticationProcessingFilter extends GenericFilterBean
implements ApplicationEventPublisherAware, MessageSourceAware {
...
// 委托给子类ProviderManager执行认证,最终由DaoAuthenticationProvider认证
// DaoAuthenticationProvider中会调用UserDetailsService#loadUserByUsername(username)接口方法
// 我们只需实现该UserDetailsService接口注入Bean容器即可
private AuthenticationManager authenticationManager;
private SessionAuthenticationStrategy sessionStrategy;
protected ApplicationEventPublisher eventPublisher;
private RememberMeServices rememberMeServices;
private AuthenticationSuccessHandler successHandler;
private AuthenticationFailureHandler failureHandler;
private SecurityContextRepository securityContextRepository;
...
private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
...
try {
// 模板模式,该方法子类实现
Authentication authenticationResult = attemptAuthentication(request, response);
// 1.
this.sessionStrategy.onAuthentication(authenticationResult, request, response);
// Authentication success
if (this.continueChainBeforeSuccessfulAuthentication) {
chain.doFilter(request, response);
}
// 成功后续处理
successfulAuthentication(request, response, chain, authenticationResult);
}
catch (InternalAuthenticationServiceException failed) {
// 失败后续处理
unsuccessfulAuthentication(request, response, failed);
}
catch (AuthenticationException ex) {
// Authentication failed
unsuccessfulAuthentication(request, response, ex);
}
}
// 模板模式,由UsernamePasswordAuthenticationFilter完成
public abstract Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException;}
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
Authentication authResult) throws IOException, ServletException {
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authResult);
// 2.
SecurityContextHolder.setContext(context);
// 3.
this.securityContextRepository.saveContext(context, request, response);
// 4.
this.rememberMeServices.loginSuccess(request, response, authResult);
if (this.eventPublisher != null) {
// 5.
this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass()));
}
// 6.
this.successHandler.onAuthenticationSuccess(request, response, authResult);
}
}
UsernamePasswordAuthenticationFilter
public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
if (this.postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
String username = obtainUsername(request);
username = (username != null) ? username.trim() : "";
String password = obtainPassword(request);
password = (password != null) ? password : "";
UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,
password);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
// 调用父类中字段去认证,最终是 UserDetailService#loadUserByUsername(String username),该接口实现类由程序员根据业务定义。
return this.getAuthenticationManager().authenticate(authRequest);
}
// ************** 重要 **************
// 这里只能通过x-www-urlencoded方式获取,如果前端传过来application/json,是解析不到的
// 非要用application/json,建议重写UsernamePasswordAuthenticationFilter方法,但由于body中内容默认只能读一次,又要做很多其他配置,比较麻烦,建议这里x-www-urlencoded
// *********************************
@Nullable
protected String obtainUsername(HttpServletRequest request) {
return request.getParameter(this.usernameParameter);
}
@Nullable
protected String obtainPassword(HttpServletRequest request) {
return request.getParameter(this.passwordParameter);
}
}
来源:https://blog.csdn.net/weixin_41866717/article/details/128880306