gpt4 book ai didi

authentication - 使用Spring Security时,请求之间是否共享SecurityContext?

转载 作者:行者123 更新时间:2023-12-04 12:40:26 25 4
gpt4 key购买 nike

在使用Spring Boot编写的rest API上使用基于无状态 token 的身份验证时,我看到一些奇怪的行为。

客户端在每个请求中都包含一个JWT token ,而我编写的用于扩展GenericFilterBean的自定义过滤器将基于 token 中的声明的身份验证对象添加到安全上下文,使用以下步骤:

SecurityContextHolder.getContext().setAuthentication(authentication);

并通过执行以下操作来清除上下文:
SecurityContextHolder.getContext().setAuthentication(null);

但是,当我开发的简单应用程序执行一系列操作时,有时会看到安全上下文设置不正确-有时对于提供 token 的请求而言,它为null。正确地调用了过滤器,还调用了setAuthencation(),但是请求未通过身份验证,并抛出403被拒绝。

如果我通过将 session 创建策略设置为STATELESS来明确关闭任何http session 管理,则此行为将停止。

有什么想法在这里会发生什么吗?安全上下文是否以某种方式在处理请求的线程之间共享?

最佳答案

根据此处的官方文档,似乎可以共享上下文:
http://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html

In an application which receives concurrent requests in a single session, the same SecurityContext instance will be shared between threads. Even though a ThreadLocal is being used, it is the same instance that is retrieved from the HttpSession for each thread. This has implications if you wish to temporarily change the context under which a thread is running. If you just use SecurityContextHolder.getContext(), and call setAuthentication(anAuthentication) on the returned context object, then the Authentication object will change in all concurrent threads which share the same SecurityContext instance. You can customize the behaviour of SecurityContextPersistenceFilter to create a completely new SecurityContext for each request, preventing changes in one thread from affecting another. Alternatively you can create a new instance just at the point where you temporarily change the context. The method SecurityContextHolder.createEmptyContext() always returns a new context instance.

关于authentication - 使用Spring Security时,请求之间是否共享SecurityContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30761297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com