Viktor Baert
Viktor Baert

Reputation: 788

Spring boot keycloak integration OAuth 2.0 Access Token Response: 401 Unauthorized: [no body]

Update: disabling client auth and authorization will not show the 401 message anymore but secured endpoints will return 403.

I'm trying to integrate keycloak core-version: 20.0.2 running from a docker container. I've started out following https://www.baeldung.com/spring-boot-keycloak but after multiple suggestions from different threads I cannot get the integration to work.

application properties:

keycloak.auth-server-url=localhost:1337
keycloak.realm=SARServices
keycloak.resource=sar-login
keycloak.public-client=false
keycloak.principal-attribute=preferred_username
keycloak.credentials.secret=NvkAdEPqbN39ubjqtrjn7dKElgLlUNLj

spring.security.oauth2.client.registration.keycloak.client-id=sar-login
spring.security.oauth2.client.registration.keycloak.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.keycloak.scope=openid
spring.security.oauth2.client.provider.keycloak.issuer-uri=https://localhost:1337/realms/SARServices
spring.security.oauth2.client.provider.keycloak.user-name-attribute=preferred_username

WebConfig:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true)
class SecurityConfig(
    private val keycloakLogoutHandler: KeycloakLogoutHandler
) {

    @Bean
    fun keycloakConfigResolver(): KeycloakConfigResolver? {
        return KeycloakSpringBootConfigResolver()
    }


    @Bean
    protected fun sessionAuthenticationStrategy(): SessionAuthenticationStrategy {
        return RegisterSessionAuthenticationStrategy(SessionRegistryImpl())
    }

    @Bean
    @Throws(Exception::class)
    fun filterChain(http: HttpSecurity): SecurityFilterChain {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/user/*")
            .hasRole("adventurer")
            .anyRequest()
            .permitAll()
        http.oauth2Login()
            .and()
            .logout()
            .addLogoutHandler(keycloakLogoutHandler)
            .logoutSuccessUrl("/")
        return http.build()
    }
}

keycloak server log:

2023-01-07 18:46:55 2023-01-07 17:46:55,045 WARN  [org.keycloak.events] (executor-thread-65) type=CODE_TO_TOKEN_ERROR, realmId=7eec0241-e69f-4d5c-8b7f-7a96926e8315, clientId=sar-login, userId=null, ipAddress=172.18.0.1, error=invalid_client_credentials, grant_type=authorization_code

docker compose:

version: '1'
services:
  postgresql:
    image: docker.io/bitnami/postgresql:latest
    environment:
      - ALLOW_EMPTY_PASSWORD=yes
      - POSTGRESQL_USERNAME=bn_keycloak
      - POSTGRESQL_DATABASE=bitnami_keycloak
    volumes:
      - 'postgresql_data:/bitnami/postgresql'
      - './certs:/etc/codelance/cert'

  keycloak:
    image: quay.io/keycloak/keycloak:latest
    command: start --hostname-port=1337
    ports:
      - "1337:8443"
    environment:
      - KC_HOSTNAME=localhost
      - KC_HTTPS_CERTIFICATE_FILE=/etc/codelance/cert/keycloakcert.pem
      - KC_HTTPS_CERTIFICATE_KEY_FILE=/etc/codelance/cert/keycloak.pem
      - KEYCLOAK_ADMIN=admin
      - KEYCLOAK_ADMIN_PASSWORD=password
    depends_on:
      - postgresql
    volumes:
      - './certs:/etc/codelance/cert'
volumes:
  postgresql_data:
    driver: local

Web response login after signing in: enter image description here

client config: enter image description hereenter image description here

Upvotes: 0

Views: 2748

Answers (1)

ch4mp
ch4mp

Reputation: 12754

First, Keycloak adapters for Spring are deprecated. Don't use it.

Are you sure you want a client and not a resource-server? In other words, are your controller methods returning template names or JSON payloads?

My answer to this other question contains the solution for both client and resource-server: Use Keycloak Spring Adapter with Spring Boot 3

Upvotes: 0

Related Questions