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

Spring中为Access Token接口配置CORS跨域解决方案

Hey there! Let's fix that CORS issue you're facing with your Spring Security + Angular setup. When your Angular frontend tries to hit the Access Token endpoint, the browser's same-origin policy blocks it because Spring isn't configured to allow cross-origin requests. Here are a couple of solid ways to enable CORS properly:

Create a dedicated configuration class to set up CORS rules across your entire application. This is the cleanest approach if you need CORS for multiple endpoints:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // Apply rules to all endpoints
                .allowedOrigins("http://localhost:4200") // Replace with your Angular app's actual URL
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // Include OPTIONS for preflight requests
                .allowedHeaders("*") // Allow all request headers (tighten this if needed for security)
                .allowCredentials(true); // Enable if your request includes cookies or auth headers
    }
}

Note: If you're deploying to production, replace "http://localhost:4200" with your actual frontend domain (never use "*" if you need allowCredentials=true—browsers block this combination).

2. Integrate CORS with Spring Security

If you're using Spring Security, its filter chain might override your global CORS settings. You need to explicitly enable CORS within your security configuration to make it work:

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.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.List;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .cors(cors -> cors.configurationSource(corsConfigurationSource())) // Enable CORS in Security
                .csrf(csrf -> csrf.disable()) // Disable CSRF if using token-based auth (like JWT)
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/api/auth/token").permitAll() // Allow public access to your token endpoint
                        .anyRequest().authenticated()
                );
        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(List.of("http://localhost:4200"));
        configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(List.of("*"));
        configuration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

This ensures Spring Security doesn't block cross-origin requests before they reach your CORS configuration.

3. Per-Endpoint CORS (For Specific Use Cases)

If you only need CORS for your Access Token endpoint (and no others), you can use the @CrossOrigin annotation directly on your controller or method:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @PostMapping("/token")
    @CrossOrigin(
        origins = "http://localhost:4200",
        allowedHeaders = "*",
        methods = {org.springframework.web.bind.annotation.RequestMethod.POST, org.springframework.web.bind.annotation.RequestMethod.OPTIONS},
        allowCredentials = true
    )
    public ResponseEntity<TokenResponse> getAccessToken(@RequestBody AuthRequest request) {
        // Your token generation logic here
        return ResponseEntity.ok(new TokenResponse("your-generated-access-token"));
    }
}

This is great for quick, targeted fixes but isn't ideal if you need CORS across multiple endpoints.

Quick Troubleshooting Tips

  • Always include OPTIONS in allowedMethods—browsers send a preflight OPTIONS request before actual POST/PUT requests.
  • If your Angular app sends an Authorization header or cookies, make sure allowCredentials=true is set (and avoid using "*" for allowedOrigins).

Once you apply one of these setups, your Angular app should be able to call the Access Token endpoint without CORS errors. Give it a test and let me know if you hit any snags!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:10:55