Spring Security登录认证流程
在上一章节,我们看到未登录时,请求被拦截然后重定向到登录页面。那Spring Security登录认证流程是怎样的呢?现在,来分析一下。
认证流程图
这幅图大致描述登录认证流程:
- 首先访问未被授权的请求
/private
资源 FilterSecurityInterceptor
过滤器拒绝这个请求并抛出AccessDeniedException
的异常。- 因为请求没有被认证,
ExceptionTranslationFilter
将开始认证并且重定向到一个地址(这个地址由AuthenticationEntryPoint
配置的,在多数情况下AuthenticationEntryPoint
的实现类都是LoginUrlAuthenticationEntryPoint
)。 - 然后浏览器重定向到该地址。
重定向实现
我们先来看一下重定向流程,在重定向过程中主要涉及:FilterSecurityInterceptor
、ExceptionTranslation
、LoginUrlAuthenticationEntryPoint
三个类。
(1)这个请求会被Spring Security的过滤器链的最后一个 FilterSecurityInterceptor
拦截下来。然后由父类判断没有授权,抛出 AccessDeniedException
异常。
(2)抛出的异常会被 FilterSecurityInterceptor
的前一个过滤器 ExceptionTranslationFilter
捕获,然后过滤器 ExceptionTranslationFilter
调用 LoginUrlAuthenticationEntryPoint#commence
方法返回给客户端302,要求客户端重定向到 /login
页面
(3)客户端发送/login
请求,/login
请求会被 DefaultLoginPageGeneratingFilter
过滤器拦截,并在该过滤器生产登录页面并返回。
默认登录页面实现
默认登录页面是由过滤器 DefaultLoginPageGenerationFilter
生成的。我们先来看一下过滤器 DefaultLoginPageGeneratingFilter
的属性和初始化过程。
DefaultLoginPageGenerationFilter属性和初始化
public class DefaultLoginPageGeneratingFilter extends GenericFilterBean {
private String loginPageUrl; // 登录页地址
private String logoutSuccessUrl; //登出成功后跳转地址
private String failureUrl; // 登录失败后跳转地址
private String formLoginEnabled;
private