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提供了登录页面,是前后端不分离的形式,前后端分离时的配置需另加配置。本文基于前后端分离模式来叙述。

基本流程如下:

Spring Security账户与密码验证实现过程

Username/Password认证可分为两部分:

  • 从HttpServletRequest中获取用户登录信息

  • 从密码存储处获取密码并比较

关于获取获取用户登录信息,Spring Security支持三种方式(基本用的都是Form表单提交,即POST方式提交):

  • Form

  • Basic

  • Digest

关于密码的获取和比对,关注下面几个类和接口:

  • UsernamePasswordAuthenticationFilter: 过滤器,父类AbstractAuthenticationProcessingFilter中组合了AuthenticationManagerAuthenticationManager的默认实现ProviderManager中又组合了多个AuthenticationProvider,该接口实现类,有一个DaoAuthenticationProvider负责获取用户密码以及权限信息,DaoAuthenticationProvider又把责任推卸给了UserDetailService

  • PasswordEncoder : 密码加密方式

  • UserDetails : 代表用户,包括 用户名、密码、权限等信息

  • UserDetailsService : 最终实际调用获取 UserDetails的接口,通常用户实现。

整个流程的UML图如下:

Spring Security账户与密码验证实现过程

前后端分离模式下配置

先来看对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测试:

登录成功登陆失败

Spring Security账户与密码验证实现过程

Spring Security账户与密码验证实现过程

AbstractAuthenticationProcessingFilter

该类是UsernamePasswordAuthenticationFilterOAuth2LoginAuthenticationFilter的父类,使用模板模式构建。

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

标签:Spring,Security,密码认证
0
投稿

猜你喜欢

  • java必学必会之线程(2)

    2023-11-09 10:22:35
  • Android中处理apple-touch-icon详解

    2023-05-09 13:21:31
  • springboot整合security和vue的实践

    2021-09-17 20:39:28
  • 关于ASP网页无法打开的解决方案

    2021-05-30 17:00:18
  • spring boot整合RabbitMQ实例详解(Fanout模式)

    2022-08-18 18:52:30
  • Java8通过CompletableFuture实现异步回调

    2022-07-31 01:43:53
  • java8 stream 如何打印数据元素

    2022-08-20 18:40:02
  • Android launcher中模拟按home键的实现

    2023-03-25 02:33:48
  • Java实现Word/Pdf/TXT转html的示例

    2023-09-03 19:57:42
  • Java8如何将Array转换为Stream的实现代码

    2022-09-15 06:41:31
  • java多线程加锁以及Condition类的使用实例解析

    2023-08-07 07:25:30
  • 一文带你弄懂Java中线程池的原理

    2023-09-10 20:59:02
  • Jackson序列化和反序列化忽略字段操作

    2022-08-29 14:01:14
  • Java高级面试题小结

    2023-11-23 07:34:00
  • 浅谈collection标签的oftype属性能否为java.util.Map

    2023-03-19 23:16:15
  • SpringBoot统一返回JSON格式实现方法详解

    2021-10-03 20:22:52
  • C#实现XML文件与DataTable、Dataset互转

    2021-06-07 04:00:27
  • Java内存模型之happens-before概念详解

    2023-11-23 03:11:50
  • android多媒体音乐(MediaPlayer)播放器制作代码

    2022-01-06 01:13:20
  • Java 实战项目锤炼之网上图书馆管理系统的实现流程

    2021-10-09 02:05:34
  • asp之家 软件编程 m.aspxhome.com