Keycloak oidc and roles

Hi, i starded out using this as a basis:

I can see roles in the token, under realm_access.roles. But they are not picked up, if I use the @RolesAllowed annotation I get “Could not navigate to ‘’”.

I’ve tried all combinations of prefixing with ROLE_, both in keycloak role name and annotation. Also ofcourse I have tried “all” fixes for this found with google, with no luck.

With @PermitAll, which is the only annotation demonstrated in the example, I am denied when not logged in, and allowed when logged in, as I should.

Spring Boot 3.3.3, Vaadin 24.4.10 and Keycloak 25.0.4

Does anyone know how I can get Spring Security to pick up the roles from the token?

This stackoverflow answer is all you need Keycloak with Spring Boot based on roles does not work, which were assigned to the user in keycloak - Stack Overflow - the important part is the checkbox include in IDToken

Nice, it works now. Keycloak was already configured correct. In the example I use as basis (from the vaadin blog) the config is a subclass of VaadinWebSecurity so I kept that as a superclass.

Then I didn’t need

    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.oauth2Login(Customizer.withDefaults());
        ...
        return http.build();
    }

because it is already configured in the @Override config method. But I included the rest, and then it worked :-) I used the role name without ROLE_ prefix in the annotation.

Thanks a bunch, I’ve tried “thousands” of other variants from StackOverflow, with no luck.

I have included the actual config I use in the comments here

I once wrote an article about that Secure Your Vaadin App with Keycloak OAuth2 Integration

Yes, looks pretty much like what I ended up with, role mapping code a little more tidy in your variant perhaps.

Only real difference I can spot is the Add to ID Token setting, in your example it is disabled, but in the above answer it is turned on, and pointed out to be the most significant setting. Let’s leave to the reader to figure out how significant it is … :0) (Could be due to different Keycloak versions, 20 vs. 25.)

It doesn’t matter. It’s only relevant for the mapper where to take the roles from.

1 Like