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

Spring Boot中如何配置HttpSecurity以满足特定权限控制需求?

搞定Spring Security OAuth2开放端点的配置问题

嘿,看起来你在Spring Security OAuth2的权限配置上遇到了麻烦对吧?你的需求很清晰:未认证用户可以访问/oauth/token拿令牌、打开/swagger-ui.html看文档,其他所有端点都得有有效令牌才能进。但目前的情况应该是无Authorization(注意是这个拼写,不是你写的Authorisation哦)头的用户没法正常访问这两个开放端点?十有八九是SecurityConfig里的规则配置出了问题,下面给你一步步解决:

核心配置要点

  • 得明确把/oauth/token和Swagger相关的所有资源都设为无需认证就能访问(别只加/swagger-ui.html,不然页面里的API文档、静态资源加载会失败)
  • 确保其余所有端点都强制要求有效令牌验证
  • 注意请求头的拼写:Spring Security默认认的是Authorization,拼写错了会导致带令牌的请求也被拦截

修正后的SecurityConfig示例(传统WebSecurityConfigurerAdapter方式)

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // REST API不需要CSRF防护,直接禁用
            .csrf().disable()
            // 保持无状态,不创建会话
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            // 配置请求授权规则
            .authorizeRequests()
                // 开放OAuth2令牌获取端点,这个本身就是给未认证用户用的
                .antMatchers("/oauth/token").permitAll()
                // 开放所有Swagger相关资源,不然页面加载不全
                .antMatchers("/swagger-ui.html", "/v2/api-docs", "/swagger-resources/**", "/webjars/**").permitAll()
                // 剩下的所有请求必须经过认证
                .anyRequest().authenticated()
            .and()
            // 启用Bearer令牌验证,这里如果是JWT令牌就用jwt(),如果是普通OAuth2令牌就用opaqueToken()
            .oauth2ResourceServer().jwt();
    }
}

如果你用的是Spring Security 5.7+的新配置方式(推荐)

现在Spring官方已经不推荐用WebSecurityConfigurerAdapter了,新的配置方式更简洁:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests(auth -> auth
                .antMatchers("/oauth/token").permitAll()
                .antMatchers("/swagger-ui.html", "/v2/api-docs", "/swagger-resources/**", "/webjars/**").permitAll()
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2.jwt()); // 令牌类型按需调整
        return http.build();
    }
}

额外要检查的点

  • CustomAuthenticationProvider:这个自定义认证逻辑只应该处理需要认证的请求,别让它干扰开放端点的放行逻辑
  • RESTAuthenticationTokenProcessingFilter:如果是自定义的令牌过滤器,记得在过滤器里先判断请求路径是不是在开放列表里,别对/oauth/token和Swagger资源做多余的验证
  • 请求头拼写:一定要确认前端发送的是Authorization: Bearer <你的令牌>,拼写错成Authorisation的话,Spring Security根本认不出这个头

这样配置完之后,未认证用户就能正常访问/oauth/token拿令牌,也能顺利打开Swagger文档页面,其他端点就必须带有效令牌才能访问啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:03:08