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

Spring Boot Security OAuth2预检请求问题求助

解决Spring Boot Security中的预检请求(Preflight)问题

兄弟,我刚帮你捋了下这个预检请求的问题,Postman正常但TS代码报错,核心原因其实是浏览器和Postman的请求逻辑不一样——Postman不会触发预检的OPTIONS请求,但浏览器会,所以问题基本出在Spring Security没处理好跨域和OPTIONS请求上,给你几个一步步排查的方案:

1. 先确保Spring Security放行OPTIONS请求

预检请求用的是OPTIONS方法,你得先让Security允许这个方法访问你的token接口。在你的Security配置类的configure(HttpSecurity http)方法里加上这段:

http.authorizeRequests()
    // 可以精准放行你的token接口的OPTIONS请求,比如你的接口是/api/auth/token
    .antMatchers(HttpMethod.OPTIONS, "/api/auth/token").permitAll()
    // 或者直接放行所有OPTIONS请求,适合调试阶段
    // .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
    .anyRequest().authenticated();

2. 配置正确的CORS跨域规则

既然是前端TS代码发请求,跨域配置是绕不开的,给你两种靠谱的配置方式:

方式一:全局CORS配置(适合大多数场景)

新建一个配置类实现WebMvcConfigurer,这样所有接口都会应用跨域规则:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                // 这里填你的前端地址,比如本地开发的http://localhost:3000
                .allowedOrigins("http://localhost:3000")
                // 必须包含OPTIONS方法,不然预检过不了
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                // 允许所有请求头,包括你可能带的Authorization之类的
                .allowedHeaders("*")
                // 如果前端需要带cookie或者认证信息,一定要开这个
                .allowCredentials(true);
    }
}

方式二:在Security配置里整合CORS(解决全局配置冲突)

有时候全局CORS和Security的配置会打架,这时候直接在Security里配置更稳妥:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(corsConfigurationSource())
            .and()
            // 其他Security配置,比如关闭CSRF(如果用JWT的话)
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/api/auth/token").permitAll()
            .anyRequest().authenticated();
    }

    // 定义CORS配置源
    private CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

3. 关闭CSRF保护(如果用JWT的话)

如果你的认证是基于JWT令牌的,那CSRF保护其实没必要开,反而会影响跨域请求,在Security配置里加上:

http.csrf().disable();

4. 顺便检查下TS代码的请求是否规范

虽然大概率是Spring端的问题,但也可以确认下TS代码有没有坑:

  • 如果是POST请求拿token,确保Content-Type和Spring端的接收方式匹配(比如application/json或者application/x-www-form-urlencoded)
  • 如果需要带cookie,记得开启withCredentials: true(以axios为例)
    给你个TS请求的示例:
import axios from 'axios';

async function fetchToken() {
    try {
        const res = await axios.post('http://localhost:8080/api/auth/token', {
            username: 'your-user',
            password: 'your-pass'
        }, {
            withCredentials: true,
            headers: {
                'Content-Type': 'application/json'
            }
        });
        console.log('拿到的token:', res.data);
    } catch (err) {
        console.error('请求出错:', err);
    }
}

如果按上面的步骤弄完还是有问题,把你的完整Security配置代码贴出来,我再帮你揪细节!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:23:40