Spring Security配置遇CORS问题,需修改SecurityConfig.java吗?
解决Spring Security下的CORS跨域访问问题
是的,你需要在SecurityConfig中添加CORS相关配置,当前代码仅处理了接口权限控制,未配置跨域请求规则,导致浏览器的OPTIONS预检请求被拦截,进而无法正常访问接口。
修改步骤:
- 在
configure(HttpSecurity http)方法中启用CORS支持,添加.cors().and():
@Override protected void configure(HttpSecurity http) throws Exception { http. cors() // 启用CORS配置 .and() .csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/login").permitAll() .antMatchers("/logout").permitAll() .antMatchers("/register").permitAll() .antMatchers("/getChecks").hasAuthority(Permission.USERS_READ.getPermission()) .antMatchers("/addCheck").hasAuthority(Permission.USERS_ADD_DOTES.getPermission()) .anyRequest() .authenticated() .and() .apply(jwtConfigurer); }
- 定义CORS配置Bean,指定允许的源、请求方法、请求头等规则:
@Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); // 根据实际需求设置允许的前端域名,比如"http://localhost:3000",用*表示允许所有 configuration.setAllowedOrigins(Arrays.asList("*")); // 允许的HTTP请求方法 configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); // 允许携带的请求头,包含Authorization和Content-Type等常用头 configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type")); // 是否允许携带凭证(如Cookie),不需要可设为false configuration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // 对所有接口路径应用该跨域配置 source.registerCorsConfiguration("/**", configuration); return source; }
说明:
浏览器发起跨域请求前会先发送OPTIONS预检请求,验证服务器是否允许跨域。上述配置会自动处理OPTIONS请求的权限校验,同时返回正确的跨域响应头,确保你的/login、/register等无需角色的接口能被正常访问。
内容的提问来源于stack exchange,提问作者erik_101
相关产品推荐
相关产品推荐

