Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >SavedRequestAwareAuthenticationSuccessHandler源码分析

SavedRequestAwareAuthenticationSuccessHandler源码分析

作者头像
jack.yang
发布于 2025-04-05 14:06:58
发布于 2025-04-05 14:06:58
5200
代码可运行
举报
运行总次数:0
代码可运行

源码分析

这个SavedRequestAwareAuthenticationSuccessHandler类是一个自定义的认证成功处理器,它继承自Spring Security的SimpleUrlAuthenticationSuccessHandler。这个类的主要功能是在用户认证成功后,尝试从请求缓存中获取用户最初尝试访问的URL(即被保护的资源),然后将用户重定向到该URL,而不是默认的成功页面。

以下是对这个类的详细讲解:

  1. 成员变量:
    • logger:用于记录日志的Log对象,方便在代码中打印日志信息。
    • requestCache:一个RequestCache对象,用于在认证过程中保存和获取用户最初尝试访问的URL。这里默认使用HttpSessionRequestCache,它使用HTTP会话来存储请求。
  2. onAuthenticationSuccess方法:
    • 当用户认证成功时,该方法会被调用。
    • 首先,从requestCache中尝试获取用户最初尝试访问的SavedRequest对象。
    • 如果savedRequestnull(即没有保存任何请求),则调用父类SimpleUrlAuthenticationSuccessHandleronAuthenticationSuccess方法,通常这会将用户重定向到默认的成功页面。
    • 如果savedRequest不为null,则进一步检查是否应该使用默认的目标URL。这通过检查两个条件来实现:
      • isAlwaysUseDefaultTargetUrl()方法返回true(即始终使用默认的目标URL)。
      • 存在一个目标URL参数(通过getTargetUrlParameter()方法获取),并且该参数在请求中存在且有值。
    • 如果上述任一条件为真,则从requestCache中移除保存的请求,并调用父类的onAuthenticationSuccess方法。
    • 如果上述条件都不满足,则清除与认证相关的请求属性(通过clearAuthenticationAttributes方法),并使用savedRequest中的重定向URL(通过getRedirectUrl方法获取)将用户重定向到最初尝试访问的页面。这通过getRedirectStrategy().sendRedirect方法实现。
  3. setRequestCache方法:
    • 这是一个setter方法,用于设置requestCache对象。这使得外部可以注入自定义的RequestCache实现,以满足特定的需求。

这个类的主要用途是提升用户体验,因为它允许用户在认证成功后直接访问他们最初尝试访问的资源,而不是总是被重定向到默认的成功页面。这在用户需要访问多个受保护的资源时特别有用,因为他们不需要在每次认证后都重新导航到他们想要的页面。

源码内容

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
/**
 * An authentication success strategy which can make use of the
 * {@link org.springframework.security.web.savedrequest.DefaultSavedRequest} which may
 * have been stored in the session by the {@link ExceptionTranslationFilter}. When such a
 * request is intercepted and requires authentication, the request data is stored to
 * record the original destination before the authentication process commenced, and to
 * allow the request to be reconstructed when a redirect to the same URL occurs. This
 * class is responsible for performing the redirect to the original URL if appropriate.
 * <p>
 * Following a successful authentication, it decides on the redirect destination, based on
 * the following scenarios:
 * <ul>
 * <li>If the {@code alwaysUseDefaultTargetUrl} property is set to true, the
 * {@code defaultTargetUrl} will be used for the destination. Any
 * {@code DefaultSavedRequest} stored in the session will be removed.</li>
 * <li>If the {@code targetUrlParameter} has been set on the request, the value will be
 * used as the destination. Any {@code DefaultSavedRequest} will again be removed.</li>
 * <li>If a {@link org.springframework.security.web.savedrequest.SavedRequest} is found in
 * the {@code RequestCache} (as set by the {@link ExceptionTranslationFilter} to record
 * the original destination before the authentication process commenced), a redirect will
 * be performed to the Url of that original destination. The {@code SavedRequest} object
 * will remain cached and be picked up when the redirected request is received (See
 * <a href="
 * {@docRoot}/org/springframework/security/web/savedrequest/SavedRequestAwareWrapper.html">SavedRequestAwareWrapper</a>).
 * </li>
 * <li>If no {@link org.springframework.security.web.savedrequest.SavedRequest} is found,
 * it will delegate to the base class.</li>
 * </ul>
 *
 * @author Luke Taylor
 * @since 3.0
 */
public class SavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    protected final Log logger = LogFactory.getLog(this.getClass());

    private RequestCache requestCache = new HttpSessionRequestCache();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
          Authentication authentication) throws ServletException, IOException {
       SavedRequest savedRequest = this.requestCache.getRequest(request, response);
       if (savedRequest == null) {
          super.onAuthenticationSuccess(request, response, authentication);
          return;
       }
       String targetUrlParameter = getTargetUrlParameter();
       if (isAlwaysUseDefaultTargetUrl()
             || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
          this.requestCache.removeRequest(request, response);
          super.onAuthenticationSuccess(request, response, authentication);
          return;
       }
       clearAuthenticationAttributes(request);
       // Use the DefaultSavedRequest URL
       String targetUrl = savedRequest.getRedirectUrl();
       getRedirectStrategy().sendRedirect(request, response, targetUrl);
    }

    public void setRequestCache(RequestCache requestCache) {
       this.requestCache = requestCache;
    }

}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-05-31,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
springsecurity 表单登录
springSecurity需要自定义配置值 基本都是继承WebSecurityConfigurerAdapter
周杰伦本人
2022/10/25
7370
Spring Security技术栈开发企业级认证与授权(八)Spring Security的基本运行原理与个性化登录实现
其中绿色部分的每一种过滤器代表着一种认证方式,主要工作检查当前请求有没有关于用户信息,如果当前的没有,就会跳入到下一个绿色的过滤器中,请求成功会打标记。绿色认证方式可以配置,比如短信认证,微信。比如如果我们不配置BasicAuthenticationFilter的话,那么它就不会生效。
itlemon
2020/04/03
7700
Spring Security技术栈开发企业级认证与授权(八)Spring Security的基本运行原理与个性化登录实现
打造REST风格的Spring Security配置
本教程介绍如何使用Spring和基于Java配置的Spring Security 4来保护REST服务。本文将重点讨论如何通过Login和Cookie来为REST API设置特定的安全配置。
烟雨平生
2023/03/07
1K0
打造REST风格的Spring Security配置
Spring Security 自定义用户认证
在 Spring Boot 集成 Spring Security 这篇文章中,我们介绍了如何在 Spring Boot 项目中快速集成 Spring Security,同时也介绍了如何更改系统默认生成的用户名和密码。接下来本文将基于 Spring Boot 集成 Spring Security 这篇文章中所创建的项目,进一步介绍在 Spring Security 中如何实现自定义用户认证。
阿宝哥
2019/11/15
1.4K0
Spring Security学习(二)
被LogoutFilter在成功注销后调用,用来进行重定向或者转发相应的目的地。注意这个接口与LogoutHandler几乎一样,但是可以抛出异常。
allsmallpig
2021/02/25
8650
Spring Security详解 顶
2020-01-05 01:57:16.482 INFO 3932 --- [ main] .s.s.UserDetailsServiceAutoConfiguration :
算法之名
2020/01/15
2.5K0
Spring Security详解
                                                                            顶
SwitchUserFilter源码解析
spring-security-web-4.2.3.RELEASE-sources.jar!/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.java
code4it
2018/09/17
5680
SpringCloud微服务实战系列(十八)Ouath2在真实场景中的应用之授权服务器
在《SpringCloud微服务实战系列(十七)Ouath2在真实场景中的应用之资源服务器》]中
品茗IT
2020/05/28
1.5K0
Spring Security 6.x OAuth2登录认证源码分析
上一篇介绍了Spring Security框架中身份认证的架构设计,本篇就OAuth2客户端登录认证的实现源码做一些分析。
fullstackyang
2024/06/20
4240
Spring Security 6.x OAuth2登录认证源码分析
Spring Security Oauth2 单点登录案例实现和执行流程剖析
OAuth是一个关于授权的开放网络标准,在全世界得到的广泛的应用,目前是2.0的版本。OAuth2在“客户端”与“服务提供商”之间,设置了一个授权层(authorization layer)。“客户端”不能直接登录“服务提供商”,只能登录授权层,以此将用户与客户端分离。“客户端”登录需要获取OAuth提供的令牌,否则将提示认证失败而导致客户端无法访问服务。关于OAuth2这里就不多作介绍了,网上资料详尽。下面我们实现一个 整合 SpringBoot 、Spring Security OAuth2 来实现单点登录功能的案例并对执行流程进行详细的剖析。
朝雨忆轻尘
2019/06/19
2.9K0
Spring Security Oauth2 单点登录案例实现和执行流程剖析
Spring Security (四) 核心过滤器源码分析
前面的部分,我们关注了Spring Security是如何完成认证工作的,但是另外一部分核心的内容:过滤器,一直没有提到,我们已经知道Spring Security使用了springSecurityFillterChian作为了安全过滤的入口,这一节主要分析一下这个过滤器链都包含了哪些关键的过滤器,并且各自的使命是什么。 4 过滤器详解 4.1 核心过滤器概述 由于过滤器链路中的过滤较多,即使是Spring Security的官方文档中也并未对所有的过滤器进行介绍,在之前,《Spring Security(
程序猿DD
2018/02/01
1.5K0
Spring Security (四) 核心过滤器源码分析
Spring Security 4 基于角色的登录例子(带源码)
原文网址: http://websystique.com/spring-security/spring-security-4-role-based-login-example/
明明如月学长
2021/08/27
1.3K0
Spring Security源码分析八:Spring Security 退出
Spring Security的退出请求(默认为/logout)由LogoutFilter过滤器拦截处理。
java干货
2021/02/19
7330
Spring Security源码分析八:Spring Security 退出
Spring Security内置过滤器详解
根据前面的示例,我们已经知道启动时会加载18个过滤器,并且已经知道了请求会匹配到DefaultSecurityFilterChain并依次通过这18个过滤器。
阿提说说
2022/12/02
1.2K0
Spring Security笔记:自定义Login/Logout Filter、AuthenticationProvider、AuthenticationToken
在前面的学习中,配置文件中的<http>...</http>都是采用的auto-config="true"这种自动配置模式,根据Spring Security文档的说明: ------------------ auto-config Automatically registers a login form, BASIC authentication, logout services. If set to "true", all of these capabilities are added (althoug
菩提树下的杨过
2018/01/19
3.1K0
Spring Security笔记:自定义Login/Logout Filter、AuthenticationProvider、AuthenticationToken
使用spring-security-oauth2作为client实现
本文主要讲一下如何使用spring security oauth2作为一个client来使用
code4it
2018/09/17
5.2K0
Spring Security源码分析之LogoutFilter
LogoutFilter过滤器对应的类路径为 org.springframework.security.web.authentication.logout.LogoutFilter 通过这个类的源
JavaEdge
2018/05/16
1.2K0
Spring Security---ONE
我们可以通过浏览器进行登录验证,默认的用户名是user.(下面的登录框不是我们开发的,是HttpBasic模式自带的)
大忽悠爱学习
2021/12/07
2K0
Spring Security---ONE
spring 用户通过交互界面登录成功事件源码分析
用户通过前端交互界面登录成功触发此事件 org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent
路过君
2023/07/24
1970
spring authorization server oidc客户端发起登出源码分析
spring-security-oauth2-authorization-server:1.2.1
路过君
2024/05/24
2720
相关推荐
springsecurity 表单登录
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验