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> {

	@Override
	public 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;
		}
		// 默认的RequestCache
		HttpSessionRequestCache defaultCache = new HttpSessionRequestCache();
		defaultCache.setRequestMatcher(createDefaultSavedRequestMatcher(http));
		return defaultCache;
	}
}

这样所有需要使用RequestCache的组件,都从HttpSecurity的sharedObjects中获取就行。大家就用的同一个对象了。

SavedRequestAwareAuthenticationSuccessHandler

public class SavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
	@Override
	public 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)))) {
			// 默认跳转,或者请求参数有值,则直接跳转到默认请求,同时清空requestCache
			this.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);
	}
}

保存请求和跳转流程

  1. 客户端请求目标地址,被服务端的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;
    	}
    }
    
  2. 安全异常处理器,将请求保存起来,并跳转到登录页
    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 valid
       		SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
       		this.securityContextHolderStrategy.setContext(context);
       		// 保存请求
       		this.requestCache.saveRequest(request, response);
       		// 跳转登录页
       		this.authenticationEntryPoint.commence(request, response, reason);
       	}
       } 
    
  3. 客户端输入凭证登录成功后,调用AuthenticationSuccessHandler跳转。至于跳转到哪里就看配置了。

总结

1、跳转的核心组件:AuthenticationSuccessHandler。
2、跳转到认证前的请求,需要RequestCache的配合。并且SavedRequestAwareAuthenticationSuccessHandlerExceptionTranslationFilter必须使用同一个RequestCache对象才行。这也意味着需要异常处理过滤器和认证处理器的配合。

后记

“”有点懒,你给我醒醒!”。不满意自己的学习态度!继续补博客吧。由于篇幅有限,之前说的功能,下次再聊哈。

  • 15
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security中,可以通过配置实现登录成功后的跳转,具体步骤如下: 1. 配置登录页面 在Spring Security的配置文件中,配置登录页面,例如: ```java @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/home") .permitAll() .and() .logout() .permitAll(); } ``` 这里的`loginPage("/login")`表示登录页面的URL是`/login`,`.defaultSuccessUrl("/home")`表示登录成功后跳转到`/home`页面。 2. 配置登录成功处理器 在Spring Security的配置文件中,配置登录成功处理器,例如: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .successHandler(loginSuccessHandler()) // 配置登录成功处理器 .permitAll() .and() .logout() .permitAll(); } @Bean public AuthenticationSuccessHandler loginSuccessHandler(){ return new AuthenticationSuccessHandler() { @Override public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { httpServletResponse.sendRedirect("/home"); // 登录成功后跳转到/home页面 } }; } } ``` 这里的`successHandler(loginSuccessHandler())`表示在登录成功后调用一个名为`loginSuccessHandler`的Bean,该Bean是一个实现了`AuthenticationSuccessHandler`接口的类,在其`onAuthenticationSuccess`方法中实现登录成功后的跳转。 以上就是在Spring Security中实现登录成功后跳转的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值