Home > Software engineering >  CORS error when calling from Angular to Spring Security OAuth enabled server
CORS error when calling from Angular to Spring Security OAuth enabled server

Time:01-30

I have an Angular project which will send a header Authorization with value Bearer <access_token>. UI is integerated to Keycloak and token is refreshed and placed on the header through angular interceptors, all fine on UI.

On the REST the server runs Spring Boot Spring Security OAuth2ResourceServer.

I have a Security Config class which enables the Spring Security which creates the default cors filter.

Yet i get CORS error on the browser running on http://localhost:4200.

So i created a separate CorsFilter bean in SpringApplication class.

@Bean
public CorsFilter getCorsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.setAllowedOriginPatterns(Arrays.asList("http://localhost:4200"));
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

Still i get the CORS error on UI.

Spring Security config below

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()        
            .antMatcher("/api/**")
            .authorizeRequests()
            .antMatchers(HttpMethod.GET)
            .hasAnyAuthority("SCOPE_read", "SCOPE_profile", "ROLE_USER")
            .antMatchers(HttpMethod.POST)
            .hasAnyAuthority("SCOPE_read", "SCOPE_profile", "ROLE_USER")
                    .anyRequest().authenticated()
        .and()
          .oauth2ResourceServer()
            .jwt();
    }
}

CodePudding user response:

After analysing for a day figured out to customise the default CorsFilter.

The fresh CorsFilter bean i defined was not recognised by spring security. So i had to customise the http.cors() as below.

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {// @formatter:off
        http.cors(corsCustomiser())        
            .antMatcher("/api/**")
            .authorizeRequests()
            .antMatchers(HttpMethod.GET)
            .hasAnyAuthority("SCOPE_read", "SCOPE_profile", "ROLE_USER")
            .antMatchers(HttpMethod.POST)
            .hasAnyAuthority("SCOPE_read", "SCOPE_profile", "ROLE_USER")
                    .anyRequest().authenticated()
        .and()
          .oauth2ResourceServer()
            .jwt();
    }//@formatter:on

    private Customizer<CorsConfigurer<HttpSecurity>> corsCustomiser() {
        return new Customizer<CorsConfigurer<HttpSecurity>>() {
            @Override
            public void customize(CorsConfigurer<HttpSecurity> t) {
                t.configurationSource(getCorsConfiguration());              
            }           
        };
    }   
    
    private CorsConfigurationSource getCorsConfiguration() {    
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.setAllowedOriginPatterns(Arrays.asList("http://localhost:4200"));
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}

CodePudding user response:

first add "/oauth/token" as below

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers(HttpMethod.OPTIONS, "/oauth/token");
} 

then set filter

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter("/*")
public class CorsFilter implements Filter {

    public CorsFilter() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization");
        response.setHeader("Access-Control-Max-Age", "3600");
        if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
    }
}
  •  Tags:  
  • Related