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:

public class FilterProvider {

    public WebMvcConfigurer corsConfiguration() {
        return new WebMvcConfigurerAdapter() {
            public void addCorsMappings(CorsRegistry registry) {
                        .allowedMethods(HttpMethod.GET.toString(), HttpMethod.POST.toString(),
                                HttpMethod.PUT.toString(), HttpMethod.DELETE.toString(), HttpMethod.OPTIONS.toString())

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 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: programming


  1. kevin
    Posted December 14, 2016 at 09:40 | Permalink

    I followed your example but still have trouble with CORS. I would really appreciate if you can take a look

  2. Valerij
    Posted April 6, 2017 at 11:44 | Permalink

    You’ve saved me the day!
    Thank you very much!

    I suppose that it would be helpful if you could mention this setting in your blog article

  3. Deepali
    Posted April 21, 2017 at 10:00 | Permalink

    Any idea if a backend microservice which uses a keycloak token when put behind Nginx needs any special configuration. The frontend is an ionic (HTML + angular) phone app.

    We are seeing failures when nginx comes into picture.

Post a Comment

Your email is kept private. Required fields are marked *