Spring Security之登录跳转
前言
登录成功后,我们可以有多个选择:跳转到应用首页、跳转到未登录时访问被拒绝的请求。除此之外,我们还有其他的相关功能点,例如:多点登录控制等等。今天,就来看看这些小功能。
登录成功后跳转
这个功能点介绍的有点晚,他是我们认证过滤器最后一涉及的,但还没有聊到的组件AuthenticationSuccessHandler负责的。
public interface AuthenticationSuccessHandler {/*** 这是默认方法* @since 5.2.0*/default void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain,Authentication authentication) throws IOException, ServletException {// 调用处理方法onAuthenticationSuccess(request, response, authentication);// 继续完成过滤器链chain.doFilter(request, response);}/*** 这是实现者需要完成的处理方法*/void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,Authentication authentication) throws IOException, ServletException;}
- SimpleUrlAuthenticationSuccessHandler
1、 他首先尝试从地址栏参数中获取目标地址,然后是请求头的Referer,最后是默认的目标地址。
2、然后通过RedirectStrategy重定向。默认的重定向策略会先检查是否为绝对路径。如果不是则拼接上ContextPath,再不对就拼接http(s): //,然后再重定向。
3、 清理上次认证失败保存在session中的认证异常 - SavedRequestAwareAuthenticationSuccessHandler
这个就是我们实现登录成功后跳转到登录前访问的地址的实现啦。他是SimpleUrlAuthenticationSuccessHandler的子类。 - ForwardAuthenticationSuccessHandler
转发处理器。将当前请求转发到某个指定的地址。
配置AuthenticationSuccessHandler
默认配置比较简单,直接在过滤器的Configurer中字段里。
private SavedRequestAwareAuthenticationSuccessHandler defaultSuccessHandler = new SavedRequestAwareAuthenticationSuccessHandler();private AuthenticationSuccessHandler successHandler = this.defaultSuccessHandler;
要修改也简单,直接通过HttpSecurity#formLogin(configurer -> configurer.successHandler(new ForwardAuthenticationSuccessHandler("/")); 就行。
跳转到登录前的页面
默认情况下,如果我们不配置,那么就会跳转到登录前的访问请求。要想跳转到认证前的页面,就必须要保存上一次的请求。所以我们一定是在安全异常处理时就将请求保存起来的。实际上,上篇咱们聊安全异常的时候也提过,在源码分析中,只不过一笔带过。但这里不展开了,感兴趣的同学可以再去看看上一篇文章的《访问拒绝异常处理原理》章节。
但显然,此处我们需要跟异常处理配合,从同一个地方将上一次的请求恢复并跳转。因此,这里我们必须要再深入认识另一个组件:RequestCache。
public interface RequestCache {// 保存请求void saveRequest(HttpServletRequest request, HttpServletResponse response);// 获取缓存的请求SavedRequest getRequest(HttpServletRequest request, HttpServletResponse response);// 获取上次保存的请求并进行封装HttpServletRequest getMatchingRequest(HttpServletRequest request, HttpServletResponse response);// 清理保存的请求void removeRequest(HttpServletRequest request, HttpServletResponse response);
}
这个组件的作用就是将当前访问失败的请求保存起来,其实主要就是保存URL,目的就是为了后续跳转。
两个实现:
- CookieRequestCache
很显然,他就是将请求保存在Cookie之中。他只保存URL。感兴趣的同学可以看看org.springframework.security.web.savedrequest.CookieRequestCache#saveRequest。 - HttpSessionRequestCache
这个就将请求保存在HttpSession中,而他保存的就比较全了。包括Cookie、RequestHeader、Locale、RequestAttribute等,全一股脑存到Session了。其实也容易理解,Cookie是保存在浏览器的,而Session是保存在后端服务器的,Cookie每次都要经过网络的,而Session不需要。一对比就能明白。
配置RequestCache
由于异常处理(ExceptionTranslationFilter)、认证成功后跳转(AbstractAuthenticationProcessingFilter)有关,因此属于HttpSecurity#sharedObjects。所以可以通过HttpSecurity.setSharedObject设置。
默认配置:HttpSessionRequestCache
可能与大家想象的可能不太一样,虽然SavedRequestAwareAuthenticationSuccessHandler、ExceptionTranslationFilter都有默认值,但是这个默认值却不能互相共享,无法协同完成跳转功能。
实际上,还有一个RequestCacheAwareFilter。但他可只有一个功能,从RequestCache中获取匹配到的上一次的请求,读取出来封装成新的Request。虽然默认的情况下,这个用不着,可能是该组件出现的晚,前面的过滤器都是直接使用RequestCache了。不过倒是不妨碍通过他配置RequestCache,当然,是通过HttpSecurity.setSharedObject设置的。
public final class RequestCacheConfigurer<H extends HttpSecurityBuilder<H>>extends AbstractHttpConfigurer<RequestCacheConfigurer<H>, H> {@Overridepublic void init(H http) {http.setSharedObject(RequestCache.class, getRequestCache(http));}private RequestCache getRequestCache(H http) {// 从HttpSecurity#sharedObjects中获取RequestCache result = http.getSharedObject(RequestCache.class);if (result != null) {return result;}// 从ApplicationContext中获取result = getBeanOrNull(RequestCache.class);if (result != null) {return result;}// 默认的RequestCacheHttpSessionRequestCache defaultCache = new HttpSessionRequestCache();defaultCache.setRequestMatcher(createDefaultSavedRequestMatcher(http));return defaultCache;}
}
这样所有需要使用RequestCache的组件,都从HttpSecurity的sharedObjects中获取就行。大家就用的同一个对象了。
SavedRequestAwareAuthenticationSuccessHandler
public class SavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {@Overridepublic void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,Authentication authentication) throws ServletException, IOException {// 从RequestCache中获取保存的请求SavedRequest savedRequest = this.requestCache.getRequest(request, response);if (savedRequest == null) {// 没有保存请求,则直接用父类的处理:跳转到根路径"/"super.onAuthenticationSuccess(request, response, authentication);return;}// 获取配置中的RequestParameter获取参数名String targetUrlParameter = getTargetUrlParameter();if (isAlwaysUseDefaultTargetUrl()|| (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {// 默认跳转,或者请求参数有值,则直接跳转到默认请求,同时清空requestCachethis.requestCache.removeRequest(request, response);super.onAuthenticationSuccess(request, response, authentication);return;}/*** 跳转到认证前的目标请求 ***/// 清理session中认证失败的标记clearAuthenticationAttributes(request);// Use the DefaultSavedRequest URL// 从保存的请求中获取到认证前的目标请求String targetUrl = savedRequest.getRedirectUrl();// 跳转到认证前的目标请求getRedirectStrategy().sendRedirect(request, response, targetUrl);}
}
保存请求和跳转流程
- 客户端请求目标地址,被服务端的AuthorizationFilter发现没有登录
public class AuthorizationFilter extends GenericFilterBean {private Authentication getAuthentication() {Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication();if (authentication == null) {// 没有登录,抛出认证异常throw new AuthenticationCredentialsNotFoundException("An Authentication object was not found in the SecurityContext");}return authentication;} } - 安全异常处理器,将请求保存起来,并跳转到登录页
public class ExceptionTranslationFilter extends GenericFilterBean implements MessageSourceAware {protected void sendStartAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,AuthenticationException reason) throws ServletException, IOException {// SEC-112: Clear the SecurityContextHolder's Authentication, as the// existing Authentication is no longer considered validSecurityContext context = this.securityContextHolderStrategy.createEmptyContext();this.securityContextHolderStrategy.setContext(context);// 保存请求this.requestCache.saveRequest(request, response);// 跳转登录页this.authenticationEntryPoint.commence(request, response, reason);}} - 客户端输入凭证登录成功后,调用AuthenticationSuccessHandler跳转。至于跳转到哪里就看配置了。
总结
1、跳转的核心组件:AuthenticationSuccessHandler。
2、跳转到认证前的请求,需要RequestCache的配合。并且SavedRequestAwareAuthenticationSuccessHandler和ExceptionTranslationFilter必须使用同一个RequestCache对象才行。这也意味着需要异常处理过滤器和认证处理器的配合。
后记
“”有点懒,你给我醒醒!”。不满意自己的学习态度!继续补博客吧。由于篇幅有限,之前说的功能,下次再聊哈。
