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 {
@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.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.
3 Comments
I followed your example but still have trouble with CORS. I would really appreciate if you can take a look http://stackoverflow.com/questions/41137766/keycloak-cors-filter-spring-boot
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 http://slackspace.de/articles/authentication-with-spring-boot-angularjs-and-keycloak/
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.