Fork me on GitHub

Programming, Internet & more

CORS with Keycloak and Spring Boot

A quick tip regarding Keycloak, Spring Boot and some kind of JavaScript UI technology. When you’re trying to connect a JavaScript UI like Angular to a backend which is secured by Keycloak you have to be aware of CORS. I’m pretty sure you already know this.

However, there is a common pitfall, you have to enable CORS 2 times. First you have to enable CORS on Spring Boot level to make sure your origin is allowed to make calls to the REST api.

This can be done with a WebMvcConfigurerAdapter like this:

@Configuration
public class FilterProvider {

    @Bean
    public WebMvcConfigurer corsConfiguration() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                        .allowedMethods(HttpMethod.GET.toString(), HttpMethod.POST.toString(),
                                HttpMethod.PUT.toString(), HttpMethod.DELETE.toString(), HttpMethod.OPTIONS.toString())
                        .allowedOrigins("*");
            }
        };
    }
}

The second time you have to enable CORS is explicitly for Keycloak. If you forget this, your UI won’t be able to connect to your REST api. To enable CORS for Keycloak you can simply add the following to your application.properties file:

# Keycloak Enable CORS
keycloak.cors = true

The configuration is simple but trust me this could easily drive you crazy if you forget it. The browser will constantly complain about missing CORS headers. Additionally this error message could be misleading because you already enabled CORS for Spring Boot, right?

So, hopefully this tip will help you the next time when you’re running into this problem with Keycloak.

Category: spring-boot

3 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *