Search code examples
spring-bootspring-securityoauth-2.0keycloak

Springboot Keycloak after authentication redirects to path "/" instead of my desired path


I am trying to setup Keycloak authentication to my Spring-boot application endpoints, I have configured the SecurityFilterChain, Whenever I hit the path api it redirects to Keycloak login interface and after successfully completing login it shows an Whitelabel Error Page, can't figure out what I have configured wrong or what am I missing.

When landing on white label error page, it logs Set SecurityContextHolder to OAuth2AuthenticationToken [Principal=Name: [user1]...... and Redirecting to /. Below is my implementation of filterChain(SecurityFilterChain) for Security configuration.

@Bean
fun filterChain(http: HttpSecurity): SecurityFilterChain {
    http
        .cors { cors ->
            cors.configurationSource(corsConfigurationSource())
        }
        .authorizeHttpRequests { authz ->
            authz
                .requestMatchers(HttpMethod.GET, "/auth/**").authenticated()
                .requestMatchers(HttpMethod.GET,"/noauth").permitAll()
                .anyRequest().permitAll()
        }
        .oauth2ResourceServer{
            it
                .jwt()
        }

        .sessionManagement{
            it
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        }
        .httpBasic().disable()
        .oauth2Login()

    return http.build()
}

Solution

  • I strongly advise that you get some more OAuth2 background. You might also find usefull tips in the tutorials I wrote (linked on the same page), which cover quite a few client and resource-server configuration use cases.

    In OAuth2, login is the responsability of clients (not resource server) and requires sessions.

    Here, you are mixing OAuth2 client and OAuth2 resource server configuration in the same security filter-chain. This isn't consistent.

    If your app is a REST API you want to be secured with JWT access tokens, remove anything related to login (again, this is the responsability of the client). You may also disable CSRF protection as you disabled sessions. Use Postman or whatever OAuth2 REST client to login and then query your API.

    If you want OAuth2 login inside your app (maybe you have server side rendered UI with Thymeleaf or something), then your app is a client and will be secured with sessions (not JWTs). Enable sessions and remove the part with resource server.

    If you want both (access authorized with sessions in some cases and with access tokens in others), then define two distinct SecurityFilterChain beans, with dintinct @Order and a securityMatcher in the first in @Order to restrict to which requests it should be applied.