Search code examples
spring-securitykeycloakspring-security-oauth2spring-cloud-gateway

Keycloak with Spring 'Invalid credentials' after login


I'm having no luck in setting up a simple Spring gateway + oauth2 client with Keycloak standalone. The keycloack part of it works fine. Wireshark shows the token correctly generated.

enter image description here

The gateway security config is as follows. I'm still not sure whether there is a need to permitAll() the login callback url. Some guides suggest that it should be the case, others dont. I suspect the oauth provider manages that part behind the scenes. Nonetheless, with or without permitAll for the "/login/*" path, the result remains the same.

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {
    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http.authorizeExchange(e -> e.anyExchange().authenticated());
        http.oauth2Login(Customizer.withDefaults());
        http.csrf().disable();
        return http.build();
    }
}

After login the redirect to https://localhost:9000/login seems incorrect, it should retry the original url, say https://localhost:9000/test-service/v1/listall/


EDIT

In order to rule out any misconfigurations, even tried a simplest possible gateway and api resource (un-authenticated) and setup simplest possible relam in keyclock. The results haven't changed :( There are dozens of articles out there doing the exact same thing.

enter image description here

Any pointers, ideas?
Many Thanks


Solution

  • I figured it out, it was an incorrect user-name-attribute. The correct value is

    user-name-attribute: preferred_username
    

    For some reason, I had it set to preferred_name. It would save a lot of debug-time if only spring oauth writes the actual error instead of a generic invalid_grant.