0

I've trying to set CORS headers for a OAuth Rest API:

@Configuration
@EnableWebSecurity
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http
            .cors().and()
            .authorizeRequests()
            .antMatchers("/oauth/token", "/oauth/authorize**", "/publica")
            .permitAll();

        http.requestMatchers().antMatchers("/funds/**").and().authorizeRequests().antMatchers("/funds/**")
            .access("hasRole('USER')");

        ...

However, I'm not seeing the CORS headers in the response (Postman, localhost) when I access /oauth/token:

enter image description here

No CORS headers e.g. Access-Control-Allow-Origin: * :(

Also, I'd like this setting to apply to all routes too (e.g. /funds) but just trying to get the /oauth/token route working first.

Do I have this in the correct place? How do I get the CORS headers to set for this /oauth/token route (and others)? As far as I'm aware, the default corsConfigurationSource ought to be picked up if defined.

Martyn
  • 6,031
  • 12
  • 55
  • 121
  • You can use the annotation `@CrossOrigin(origins = "*", maxAge = 3600)` on method head. – Jonathan JOhx Nov 23 '19 at 19:05
  • But I don't own the method that's mapped to `/oauth/token`, so I can't use it for that, it's part of Spring Security. I could only apply this to my own routes (e.g. /funds/**) – Martyn Nov 23 '19 at 19:12
  • 1
    Oh right, so you might implement a filter so that you can add `the cors response and/or configuration` – Jonathan JOhx Nov 23 '19 at 20:45
  • Thanks. Seems to give me a lot of control over the response that way. I followed this example - https://stackoverflow.com/questions/36809528/spring-boot-cors-filter-cors-preflight-channel-did-not-succeed – Martyn Nov 23 '19 at 21:30
  • Cool, nice to hear that you have a solution :) – Jonathan JOhx Nov 24 '19 at 03:14
  • Actually, the POST request has the correct headers, but it's returning 401 on the pre-flight OPTIONS request so currently looking into why that is. – Martyn Nov 24 '19 at 05:01

0 Answers0