How to add CORS to outh2/resource server in Spring Boot 2.x?

Viewed 430

I have an oauth server and a resource server that I have created with JWT.

I also created an angular front end with 2 buttons: enter image description here

The first button calls the auth server and gets the JWT token and adds it to the input box.

The second button calls the rest server with the JWT token as a bearer Authorisation http header.

Calling the 2 services from PostMan works perfectly but I cannot get the CORS setup correctly configured for the back end services.

Both buttons are giving me the below error:

Access to XMLHttpRequest at 'http://localhost:8085/oauth/token' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.

I added all 3 of these projects to my public github repo.

enter image description here

I have tried to add CORS with several ways:

The config on the resource rest service is smaller so I will outline that here I tried adding the default .cors() on the HttpSecurity as well as setting it manually in the corsConfigurationSource() method.

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.csrf().disable()
                .cors()
                .and().authorizeRequests().anyRequest().authenticated()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);

        //I tried manually configured the cors as well
        /*http.csrf().disable()
                .cors().configurationSource(corsConfigurationSource())
                .and().authorizeRequests().anyRequest().authenticated();
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);*/
    }

   /* @Bean
    CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST"));
        configuration.setAllowCredentials(true);
        //the below three lines will add the relevant CORS response headers
        configuration.addAllowedOrigin("*");
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
  */
}

I also tried adding a servlet filter

@Component @Order(Ordered.HIGHEST_PRECEDENCE) public class SimpleCorsFilter implements Filter { @Override public void init(final FilterConfig filterConfig) throws ServletException {

}
@Override
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws

IOException, ServletException {

    final HttpServletResponse response = (HttpServletResponse) servletResponse;
    final HttpServletRequest request = (HttpServletRequest) servletRequest;

    response.addHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "content-type, x-requested-with, authorisation");

    if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        filterChain.doFilter(servletRequest, servletResponse);
    }

}
@Override
public void destroy() {

} }

Just can't get it to work. Can anyone please give me some guidelines here?

2 Answers

Silly mistake on my end as in both my SimpleCorsFilter.java files I specified that authorisation header tags are allowed but it is not authorisation with an S but with a Z.

Changing both the files in my config server

response.setHeader("Access-Control-Allow-Headers", "content-type, x-requested-with, Authorization");

Extends your class with withWebMvcConfigurer rather than WebSecurityConfigurerAdapter. The override the following method:

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE").allowedHeaders("*");
    }

It should add the origin. You can play with '*' and make many combination. I have given you idean now it is your turn to play with this API.

Related