You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security在Chrome运行正常但Postman无需授权可访问GET接口

问题根因与解决方法

核心问题原因

  • 安全配置未补全全局请求规则,也未开启方法级权限校验,同时Postman大概率残留了之前登录的有效Session凭证,才会出现两端表现不一致的情况。

具体解决步骤

  1. 补全Web安全全局规则

在SecurityConfiguration的configure(HttpSecurity http)方法的authorizeRequests()配置块末尾,添加anyRequest().authenticated(),确保所有未显式声明permitAll的路径都需要登录后才能访问,修改后的配置块如下:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http./*sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
            and().*/
                authorizeRequests()
                .antMatchers("/api/players").hasAnyRole("ADMIN")
                .antMatchers("/api/organizers").hasAnyRole("ADMIN")
                .antMatchers("/api/events").permitAll()
                .antMatchers("/h2-console/**").permitAll()
                // 新增下面这行,所有未匹配的请求都需要登录
                .anyRequest().authenticated()
            .and()
                .formLogin()
                .successHandler(successHandler)
                .permitAll()
            .and()
                .logout()
                .permitAll()
            /*.and()
            .csrf().disable()*/;
}
  1. 开启方法级权限校验

@PreAuthorize注解默认不会生效,需要在SecurityConfiguration类上添加@EnableGlobalMethodSecurity(prePostEnabled = true)注解,才能让你在Controller中写的角色校验、所有者校验规则生效:

@Configuration
@EnableWebSecurity
@EnableTransactionManagement
// 新增下面这行注解
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    // 原有代码不变
}
  1. 清理Postman残留凭证

打开Postman对应请求的「Cookies」面板,清除目标域名下的所有Cookie,同时检查「Authorization」标签确认没有配置默认的认证信息,再重新发送请求测试,就能复现和Chrome一致的未授权拦截效果。

  1. 可选:适配纯API场景

如果你做的是前后端分离的纯API服务,不需要页面跳转,可以把你注释掉的无状态Session配置和CSRF关闭配置放开,避免Session复用导致的权限校验异常,同时适配API调用的无状态特性。

额外提示

你当前用的NoOpPasswordEncoder是明文密码编码器,仅可用于测试,生产环境请替换为BCryptPasswordEncoder等支持加密的密码编码器。

内容的提问来源于stack exchange,提问作者JustM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 18:15:03