Spring Security:在 SecurityContext 中找不到 Authentication 对象

2023-12-11

以下配置(filterChain)在 SpringBoot-2.7.5 中工作正常,但在我尝试在 SpringBoot-3.0.0-RC1 中测试它之后,它不起作用并显示以下消息,如果想要迁移,我需要更改任何内容到 Spring-Boot-3.0.0。谢谢。

{ “时间戳”:1667794247614, “状态”:401, "error": "未经授权", "message": "在 SecurityContext 中未找到身份验证对象", “路径”:“/api/admin/1”}

 @Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable()
        .exceptionHandling().authenticationEntryPoint(jwtAuthenticationProvider).and()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
        .authorizeRequests()
        .antMatchers("/**").permitAll()            
        // private endpoints
        .anyRequest().authenticated();

    http.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class);

    return http.build();
}

以下是jwtTokenFilter:

@Component
public class **JwtTokenFilter** extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Autowired
    private JPAUserDetailService jpaUserDetailService;

    

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        // Get authorization header and validate
        final String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        
        if (isEmpty(header) || !header.startsWith("Bearer ")) {
            chain.doFilter(request, response);
            return;
        }

        // Get jwt token and validate
        final String token = header.split(" ")[1].trim();
        
        if (!jwtTokenUtil.validate(token)) {
                                    
            chain.doFilter(request, response);
            
            return;
        }

        // Get user identity and set it on the spring security context
        UserDetails userDetails = jpaUserDetailService.loadUserByUsername(jwtTokenUtil.getUsername(token));

        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, (userDetails == null ? null : userDetails.getAuthorities()));

        
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

        SecurityContextHolder.getContext().setAuthentication(authentication);
                
        chain.doFilter(request, response);
    }

}

在 Spring Security 6 中,默认行为是SecurityContextHolderFilter只会读取SecurityContext from SecurityContextRepository并将其填充到SecurityContextHolder。用户现在必须明确保存SecurityContextSecurityContextRepository如果他们想要SecurityContext在请求之间保持不变。只需写入即可消除歧义并提高性能SecurityContextRepository (i.e. HttpSession)当有必要时。

SecurityContextHolder.setContext(securityContext);
securityContextRepository.saveContext(securityContext, httpServletRequest, httpServletResponse);

See https://docs.spring.io/spring-security/reference/5.8/migration.html#_explicit_save_securitycontextrepository

如果这不起作用,请尝试返回到 5.x 默认值:

http
    .securityContext((securityContext) -> 
            .requireExplicitSave(false)
    )
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Security:在 SecurityContext 中找不到 Authentication 对象 的相关文章

随机推荐

  • Android应用程序没有启动图标

    我已经组装了一个简单的应用程序 当我安装该应用程序时 会显示图标 但安装后就没有启动图标 这是我的 AndroidManifest xml
  • 本地主机的 Google 地图 API 密钥

    如何让 Google 地图 API 密钥在本地主机上工作 我创建了一个 API 密钥 并在引荐来源网址下添加了以下内容 Accept requests from these HTTP referrers websites Optional
  • 如何在 Chartist.js 中使用插件?

    我正在使用 Chartist js 制作饼图组件 我想使用图例插件https codeyellowbv github io chartist plugin legend 我的饼图中没有得到图例 请参阅下面的屏幕截图 Code import
  • 多线程中boost asio中的随机EOF

    我对 boost asio 还很陌生 我正在经历随机文件结尾在多线程服务器中 我可以在这个小例子中重现我的问题 Server 这是一个简单的回显服务器 该协议很简单 1 客户端连接 2 服务器读取一个字节 该字节是要读取和发回的字符串的长度
  • 如何更改 Windows 8 动态磁贴文本颜色?

    我正在创建一个 Windows 8 应用程序 我想在其中更改活动磁贴的前景 我找到了一个模板集但没有找到任何方法来改变动态图块的文本颜色 我在我的应用程序中编写了以下模板代码
  • 禁用元素属性排序

    有没有办法禁用元素属性的排序 以便当 allowedContent 设置为 true 时 checkDirty 能够正常工作 属性排序示例here div simplesimple div 即使用户实际上没有更改 ckeditor 用户界面
  • 在函数中更新 matplotlib 图像

    我有一个处理图像的循环 我希望在每 100 次迭代时使用 matplotlib 在单个输出窗口中显示图像 所以我试图编写一个函数 它将采用 numpy 张量作为输入并显示相应的图像 这是我所拥有的不起作用的内容 def display im
  • Nokogiri 可以搜索“?xml-stylesheet”标签吗?

    我需要解析 XML 样式表 使用 Nokogiri 我尝试过 doc search xml stylesheet first href 但我收到错误 on error unexpected after Nokogiri CSS Syntax
  • 如何在实体框架中访问context.Database.SqlQuery?

    我正在尝试遵循本教程 http blogs msdn com b diego archive 2012 01 10 how to execute stored procedures sqlquery in the dbcontext api
  • 无法将文件从 docker-compose 挂载复制到主机

    我无法将 Selenium 测试生成的文件复制到安装到主机的 docker 容器内的文件夹中 这是我的撰写文件的样子 selenium image selenium standalone chrome expose 4444 tests b
  • 使用 boost asio 重用套接字

    我尝试使用 boost asio 套接字 绑定到本地地址 端口组合 效果很好 不起作用的是 一旦套接字和应用程序停止并重新启动 就重新使用套接字 open the socket it would also be opened by the
  • Google Actions sdk 无法从 Firebase 存储中播放 ssml 中的音频

    Google Actions SDK 无法从 Firebase 存储播放 SSML 音频标记中的音频文件 虽然我可以播放维基百科上相同的 ogg 格式文件 https upload wikimedia org wikipedia en 9
  • CSS媒体查询处理新的高分辨率手机,同时忽略平板电脑

    根据我的研究 新款智能手机人像分辨率高达800px平板电脑最低纵向分辨率 600px 现在 我尝试使用媒体查询将移动 css 渲染到支持高达 800px 分辨率的手持设备 但我遇到的问题是旧平板电脑 例如具有 768px 纵向分辨率的 ip
  • 如果用户在java中关闭浏览器,如何清除httpsession

    如果消费者关闭浏览器窗口 我试图清除 HttpSession 我不知道该怎么做 请帮助我 感谢和问候 却克里 如果您可以让浏览器 可靠地 通知服务器用户已关闭窗口 那么服务器可以调用session invalidate 根据 ejay fr
  • 快速改变图像的色调

    I am new to swift and trying to achieve this essentially This image to 这张图片 gt 我正在使用这个代码从这里更改图像的色调但未获得所需的输出 func tint im
  • 使用 h5py 沿新轴将数据添加到现有 h5py 文件

    我有一些生成 3d Numpy 数组的示例代码 然后我使用 h5 文件将此数据保存到 h5py 文件中 然后我如何沿着第四维 附加 第二个数据集 或者 我如何沿着现有的第四维 或新轴 编写另一个 3D 数据集 h5文件 我已经阅读了我能找到
  • 如何在 Google App Engine 中使用自定义 Python 库和应用程序?

    我想知道如何在 Google App Engine 的 django nonrel 中安装和使用第三方库和 或应用程序 目前我的 Web 应用程序使用 django nonrel 我想安装 github 中提供的一些库 通常 库需要通过 p
  • 获取用户详细信息、计算年龄并显示所有信息的程序

    我启动了一些代码 但在将用户字符串输入保存到变量中时遇到问题 使用 ReadString 我可以提示用户输入字符串 但是将用户输入保存到名为 AskName1 的变量中 然后显示 AskName1 中保存的信息后 我发现它保存了用户输入的字
  • R中使用循环处理文件夹中的所有文件

    我需要处理一个文件夹中的所有文件 并且文件是按顺序命名的 所以我认为这是循环的好时机 处理单个文件的代码很简单 df lt read table CLIM0101 WTG skip 3 header TRUE df lt df 1 df y
  • Spring Security:在 SecurityContext 中找不到 Authentication 对象

    以下配置 filterChain 在 SpringBoot 2 7 5 中工作正常 但在我尝试在 SpringBoot 3 0 0 RC1 中测试它之后 它不起作用并显示以下消息 如果想要迁移 我需要更改任何内容到 Spring Boot