tutorials icon indicating copy to clipboard operation
tutorials copied to clipboard

Spring 3.1.x and Keycloak 22.x OAuth2 Tutorial not working

Open OtenMoten opened this issue 2 years ago • 2 comments

Article and Module Links "Spring-Boot-Keycloak" @ Github "Spring-Boot-Keycloak" @ Baeldung Website

Describe the Issue

The following code is not working in Spring 3.1.5 and Keycloak 22.0.5 with OIDC via OAUTH2, because I can remove the role user in Keycloak and still can access the /customers enpoint.

@Configuration
@EnableWebSecurity
class SecurityConfig {

    private final KeycloakLogoutHandler keycloakLogoutHandler;

    SecurityConfig(KeycloakLogoutHandler keycloakLogoutHandler) {
        this.keycloakLogoutHandler = keycloakLogoutHandler;
    }

    @Bean
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
    }

    @Order(1)
    @Bean
    public SecurityFilterChain clientFilterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .requestMatchers(
                        new AntPathRequestMatcher("/"),
                        new AntPathRequestMatcher("/js/**"),
                        new AntPathRequestMatcher("/css/**"),
                        new AntPathRequestMatcher("/font/**")
                )
                .permitAll()
                .anyRequest()
                .authenticated();
        http.oauth2Login()
                .and()
                .logout()
                .addLogoutHandler(keycloakLogoutHandler)
                .logoutSuccessUrl("/");
        return http.build();
    }

    @Order(2)
    @Bean
    public SecurityFilterChain resourceServerFilterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .requestMatchers(new AntPathRequestMatcher("/customers*"))
                .hasRole("USER")
                .anyRequest()
                .authenticated();
        http.oauth2ResourceServer((oauth2) -> oauth2
                .jwt(Customizer.withDefaults()));
        return http.build();
    }

    @Bean
    public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
        return http.getSharedObject(AuthenticationManagerBuilder.class)
                .build();
    }
}

Expected Behavior The endpoint /customers should be restricted if the role "user" is removed in Keycloak from a user.

Screenshots

OAuth2AuthenticationToken [Principal=Name: [[email protected]], Granted Authorities: [[OIDC_USER, SCOPE_email, SCOPE_openid, SCOPE_profile]], User Attributes: [{at_hash=SDlv04mxz7mjKqvp36vMLw, sub=c9ce52ef-0b65-4af9-a5ff-0ef84c5e5806, resource_access={app={roles=[member]}, account={roles=[manage-account, manage-account-links, view-profile]}}, email_verified=true, iss=https://MyKeycloakDomain.com/realms/MyRealm, typ=ID, [email protected], given_name=Kevin, nonce=KeAWgOor7dsAqWQo1K8jm0K_H8EDEHWxalZecaB4KXk, sid=2f35089a-9e35-4ca1-b1f8-aadc5990bb2a, aud=[app], acr=1, azp=app, auth_time=2023-11-20T09:19:24Z, name=Kevin Surname, exp=2023-11-20T09:24:24Z, session_state=2f35089a-9e35-4ca1-b1f8-aadc5990bb2a, family_name=Surname, iat=2023-11-20T09:19:24Z, [email protected], jti=751e18c1-9c3d-4edc-9926-786b465c2797}], Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=BBCFD5155D3ECD8B46C6E4049E95186F], Granted Authorities=[OIDC_USER, SCOPE_email, SCOPE_openid, SCOPE_profile]]

As you can, even if the role user is assigned to my account, it's no in Granted Authorities. The role is stored in resource_access={app={roles=[member]}

Environment (please complete the following information):

  • OS: WINDOWS
  • Browser: BRAVE
  • Version Keycloak: 22.0.5
  • Version Spring: 3.1.5

Additional Context I just created the Keycloak realm like in te tutorial, only create the realm, create the user and assign the role. I also added a second role named "admin" and protected endpoints /admin - doesn't work.

OtenMoten avatar Nov 20 '23 09:11 OtenMoten

Hey, @OtenMoten.

Thanks for the feedback. We'll look into this.

This issue will remain open until then.

ulisseslima avatar Nov 20 '23 22:11 ulisseslima

Dear @ulisseslima and community,

thanks for awesome work until here.

I found a pretty solution for Spring 3.1.5 as well as 3.2.0 and Keycloak 22 as well as 23.

I'm now working on finalizing the code - it will be inserted here.

[PLACEHOLDER]

Thanks for your patience!

OtenMoten avatar Nov 28 '23 09:11 OtenMoten

hi @OtenMoten , where can I have a look to your updates, please ;)

anthonydenecheau avatar Dec 28 '23 14:12 anthonydenecheau

@OtenMoten Any updates on this issue would be highly appreciated. If there is an earlier version of Keycloak where it works, please suggest.

vsbgugan avatar Jan 17 '24 12:01 vsbgugan

Hello, We applied the fix. The issue should be resolved now. The code and the article have been updated to reflect the changes.

kasramp avatar Jan 22 '24 07:01 kasramp

Dear @vsbgugan and @anthonydenecheau, I really appreciate your patience. I'm very busy, but I haven't forgotten you.

Before I drop my code, what has changed @kasramp?

OtenMoten avatar Jan 22 '24 08:01 OtenMoten