首页 > 其他分享 >spring security 6.0.8(boot 3.0.13)自定义 filter 踩坑-已解决

spring security 6.0.8(boot 3.0.13)自定义 filter 踩坑-已解决

时间:2024-04-03 13:33:58浏览次数:19  
标签:29001 13 自定义 spring appLoginFilter Content localhost AppLoginFilter

spring boot 3.0.13(3.1.10)

spring security 6.0.8(6.1.8)

--

 

官方文档:

https://docs.spring.io/spring-security/reference/index.html

写文时最新为 6.2.3 。 

 

说明,先是用 spring boot 3.1.10 测试,失败,降低到 3.0.13 仍然失败。

 

开发

建立了 AppLoginFilter,实现了 attemptAuthentication 方法。

在 AppSecurityConfig 配置了:

@Configuration
@RequiredArgsConstructor
@Slf4j
public class AppSecurityConfig {

    @Bean
    public AppLoginFilter appLoginFilter(AuthenticationManager authenticationManager) throws Exception {
        AppLoginFilter appLoginFilter = new AppLoginFilter();

        appLoginFilter.setAuthenticationSuccessHandler(new AppLoginSuccessHandler());
        appLoginFilter.setAuthenticationFailureHandler(new AppLoginFailureHandler());

        appLoginFilter.setAuthenticationManager(authenticationManager);

        // todo more

        return appLoginFilter;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http,
                                                   AppLoginFilter appLoginFilter,
                                                   AuthenticationManager authenticationManager)

throws Exception { http .authorizeHttpRequests((authorize) -> authorize
.anyRequest().authenticated()
)
.csrf(csrf -> csrf.disable())
.cors(cors -> cors.disable())
.addFilterAt(appLoginFilter, UsernamePasswordAuthenticationFilter.class)
.formLogin(formlogin -> formlogin.disable())
.httpBasic(httpbasic -> httpbasic.disable()) ;   return http.build(); }   // more   }

登录接口:/app/login。

另外开发了测试接口:/test/getAppName。

 

发现问题

测试时,/app/login 正常调用,也有 Set-Cookie 响应头。

可是,使用  Set-Cookie 的 Cookie 访问 /test/getAppName 接口时,被拒绝了。

C:\Users\Mi>curl -v -X POST http://localhost:29001/app/login -H "Content-Type: application/json"  -d "{\"username\": \"user\", \"password\":\"111\"}"
Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying [::1]:29001...
* Connected to localhost (::1) port 29001
> POST /app/login HTTP/1.1
> Host: localhost:29001
> User-Agent: curl/8.4.0
> Accept: */*
> Content-Type: application/json
> Content-Length: 38
>
< HTTP/1.1 200
< Set-Cookie: JSESSIONID=43935860065AA00C85F6256735D1F368; Path=/; HttpOnly
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 0
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Tue, 02 Apr 2024 14:18:24 GMT
<
{"code":200,"data":true,"message":"登录成功","timestamp":1712067504358}* Connection #0 to host localhost left intact

C:\Users\Mi>
C:\Users\Mi>curl -v http://localhost:29001/test/getAppName -H "Cookie: JSESSIONID=43935860065AA00C85F6256735D1F368"
*   Trying [::1]:29001...
* Connected to localhost (::1) port 29001
> GET /test/getAppName HTTP/1.1
> Host: localhost:29001
> User-Agent: curl/8.4.0
> Accept: */*
> Cookie: JSESSIONID=43935860065AA00C85F6256735D1F368
>
< HTTP/1.1 403
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 0
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Content-Length: 0
< Date: Tue, 02 Apr 2024 14:18:42 GMT
<
* Connection #0 to host localhost left intact

 

后台出现一条警告日志:

WARN 5256 --- [io-29001-exec-3] o.s.w.s.h.HandlerMappingIntrospector     : Cache miss for REQUEST dispatch to '/test/getAppName' (previous null). Performing MatchableHandlerMapping lookup. This is logged once only at WARN level, and every time at TRACE.

忽略该信息。

 

解决方案

给 自定义 filter 设置 SecurityContextRepository 为 HttpSessionSecurityContextRepository 即可。

SecurityContextRepository repo = new HttpSessionSecurityContextRepository();

appLoginFilter.setSecurityContextRepository(repo);

添加后,再次测试,成功。

 

说明,该方法设置了 AbstractAuthenticationProcessingFilter 的 securityContextRepository 属性,其默认值为:

private SecurityContextRepository securityContextRepository = new RequestAttributeSecurityContextRepository();

 

调试过程

在 自定义的 AppLoginFilter 的 父类 AbstractAuthenticationProcessingFilter#325 中有一个 successfulAuthentication 函数,其中会调用:

this.securityContextHolderStrategy.setContext(context);

调试发现,这里的 this.securityContextHolderStrategy 值为 RequestAttributeSecurityContextRepository 实例,而不是 HttpSessionSecurityContextRepository 实例。

而在 SecurityContextHolderFilter 中,其值为 DelegatingSecurityContextRepository 实例——包含两个 SecurityContextRepository,其中一个是  HttpSessionSecurityContextRepository 。

 

官方文档:SecurityContextRepository

Persisting Authentication # SecurityContextRepository

https://docs.spring.io/spring-security/reference/servlet/authentication/persistence.html

The HttpSessionSecurityContextRepository associates the SecurityContext to the HttpSession. 

The RequestAttributeSecurityContextRepository saves the SecurityContext as a request attribute to make sure the SecurityContext is available for a single request that occurs across dispatch types that may clear out the SecurityContext.

 

---END---

ben发布于博客园

本文链接:

https://www.cnblogs.com/luo630/p/18111645

 

ben发布于博客园

ben发布于博客园

 

标签:29001,13,自定义,spring,appLoginFilter,Content,localhost,AppLoginFilter
From: https://www.cnblogs.com/luo630/p/18111645

相关文章

  • springboot实战---5.最简单最高效的后台管理系统开发
    ......
  • 【附源码】计算机毕业设计影评网站系统(java+springboot+mysql+mybatis+论文)
    本系统(程序+源码)带文档lw万字以上  文末可领取本课题的JAVA源码参考系统程序文件列表系统的选题背景和意义影评网站系统是一个专注于电影评论和评分的在线平台,旨在为观众提供一个交流观影体验、分享观点和发现新片的社区。随着电影产业的蓬勃发展,人们对于电影的需求和品......
  • 【附源码】计算机毕业设计智慧外贸平台(java+springboot+mysql+mybatis+论文)
    本系统(程序+源码)带文档lw万字以上  文末可领取本课题的JAVA源码参考系统程序文件列表系统的选题背景和意义智慧外贸平台是一种基于互联网技术的智能化外贸服务平台,旨在帮助外贸企业提高业务效率、降低成本、提升竞争力。随着全球化的不断深入和国际贸易竞争的加剧,传统的......
  • MySQL数据库报错:Can‘t create/write to file ‘/tmp/ibXXX‘ (Errcode: 13 - Permiss
    在进行MySQL数据库的安装和配置过程中,用户有时会遇到各种错误信息,这些错误可能会阻碍安装过程或初次运行。理解和解决这些错误对于确保数据库平稳运行至关重要。本文旨在探讨MySQL安装过程中可能出现的一个特定错误,提供关于该错误的详细信息、可能的原因及相应的解决方案。......
  • 洛谷题单指南-图的基本应用-P1363 幻象迷宫
    原题链接:题意解读:迷宫可以无限扩展,对第一个样例进行模拟,扩展4块的示意图:从起点S,沿着红色虚线,是可以无限走下去的,要判断是否能够无限走下去。解题思路:直观上,会考虑把迷宫复制多块,但是会面临2个问题:1、内存可能爆掉2、如何有效判断可以无限走下去?只考虑竖向或者横向连通是不......
  • springboot之MybatisPlus
    文章目录一、ORM二、mybatis实际操作三、mybatis-plus一、ORM简单来说ORM就是一个能够帮我们把java中Bean类映射到数据库中。使用mybatis-plus。配置架包<!--MyBatisPlus依赖--><dependency><groupId>com.baomidou</groupId>......
  • Spring进阶篇(7)-TransactionSynchronizationManager(事务监听)
    转载自:https://www.jianshu.com/p/4b5eb29cc6d9JAVA&&Spring&&SpringBoot2.x—学习目录TransactionSynchronizationManager是事务同步管理器。我们可以自定义实现TransactionSynchronization类,来监听Spring的事务操作。可以在事务提交之后,回调TransactionSynchronization......
  • 面试类 - Spring基础(一)
    1.Spring是什么?特性?有哪些模块?                                 SpringLogo一句话概括:Spring是一个轻量级、非入侵式的控制反转(IoC)和面向切面(AOP)的框架。2003年,一个音乐家RodJohnson决定发......
  • B82793S0513N201 共模扼流圈滤波器电感 51uH 800mA
    B82793S0513N201是一款由TDK(东电化)公司生产的数据线扼流圈,用于电信领域的xDSL变压器。制造商:TDK产品品种:共模扼流圈/滤波器RoHS:详细信息系列:B82793S安装风格:PCBMount端接类型:SMD/SMT通道数量:1Channel电感:51uH容差:30%最大直流电流:800mA最......
  • springboot中的Lombok的使用
    1.Lombok       属于一种对实体类进行简化配置的功能操作,通过@Data实现实体类中get和set方法省略行为。2.测试方式  第一步:创建一个springboot的项目,并同时选择需要的依赖         第二步:创建bean实体类,同时使用@Data注解       第三步:测试,此......