Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to build spring based project for authentication using keycloak

Problem statement

I am unable to build by spring boot project, I want to secure my app via. key cloak.

Expected Output

Project build successful, and when I hit the rest URL it will redirect to key cloak page for authentication.

EmployeeRestController

@RestController
public class EmployeeRestController {

  @GetMapping(path = "/username")
  public String getAuthorizedUserName() {
    return "Username Returned";
  }

  @GetMapping(path = "/roles")
  public String getAuthorizedUserRoles() {
    return "Roles Returned";
  }
}

Startup

@SpringBootApplication
public class Startup {

  public static void main(String[] args) {
    SpringApplication.run(Startup.class, args);
  }
}

application properties

server.port=8085

keycloak.realm=wow
keycloak.auth-server-url=http://localhost:8180/auth
keycloak.resource=wow-client
keycloak.public-client=true
keycloak.securityConstraints[0].authRoles[0]=user
keycloak.securityConstraints[0].securityCollections[0].patterns[0]=/*

pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.keycloak/keycloak-spring-boot-starter -->
    <dependency>
        <groupId>org.keycloak</groupId>
        <artifactId>keycloak-spring-boot-starter</artifactId>
        <version>7.0.0</version>
    </dependency>
</dependencies>

ErrorLog

2019-09-16 17:44:24.525  INFO 10396 --- [           main] com.diwakar.Startup                      : Starting Startup on diwakarb with PID 10396 (started by diwakarb in E:\DB Godam\Sample-KeyCloak-Project)
2019-09-16 17:44:24.527  INFO 10396 --- [           main] com.diwakar.Startup                      : No active profile set, falling back to default profiles: default
2019-09-16 17:44:25.419  WARN 10396 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tomcatServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedTomcat.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.keycloak.adapters.springboot.KeycloakAutoConfiguration': Unsatisfied dependency expressed through method 'setKeycloakSpringBootProperties' parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2019-09-16 17:44:25.429  INFO 10396 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-09-16 17:44:25.531 ERROR 10396 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 1 of method setKeycloakSpringBootProperties in org.keycloak.adapters.springboot.KeycloakBaseSpringBootConfiguration required a bean of type 'org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver' that could not be found.


Action:

Consider defining a bean of type 'org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver' in your configuration.


Process finished with exit code 1

Note : Please consider key cloak is correctly configured

like image 375
Diwakar Bhatt Avatar asked Sep 16 '19 12:09

Diwakar Bhatt


Video Answer


3 Answers

I got same issue using springboot-2.2.0/keycloak-7.0.1. I moved the bean KeycloakSpringBootConfigResolver to another configuration file and it works.

@Configuration
public class BeanKeycloakConfiguration {
    @Bean
    public KeycloakSpringBootConfigResolver KeycloakConfigResolver() {
        return new KeycloakSpringBootConfigResolver();
    }
}`
like image 173
Luan Gazin Avatar answered Oct 06 '22 17:10

Luan Gazin


It's a known problem with the Keycloak Spring Boot Adapter, starting from version 7.0.0. It has been addressed in this related question: Issues running example keycloak spring-boot app and documented on the project Jira here: https://issues.jboss.org/browse/KEYCLOAK-11282

An alternative solution is to declare a custom KeycloakSpringBootConfigResolver bean with an explicit KeycloakSpringBootProperties parameter, which makes Spring Boot read correctly the Keycloak configuration from the application.properties file.

@Configuration
public class MyKeycloakSpringBootConfigResolver extends KeycloakSpringBootConfigResolver {
    private final KeycloakDeployment keycloakDeployment;

    public MyKeycloakSpringBootConfigResolver(KeycloakSpringBootProperties properties) {
        keycloakDeployment = KeycloakDeploymentBuilder.build(properties);
    }

    @Override
    public KeycloakDeployment resolve(HttpFacade.Request facade) {
        return keycloakDeployment;
    }
}

If using also Spring Security, then you need to define this primary bean in the security configuration class as well, returning your custom KeycloakSpringBootConfigResolver bean.

@Bean
@Primary
public KeycloakConfigResolver keycloakConfigResolver(KeycloakSpringBootProperties properties) {
    return new MyKeycloakSpringBootConfigResolver(properties);
}
like image 43
Thomas Vitale Avatar answered Oct 06 '22 18:10

Thomas Vitale


A note on the circular dependency problem.

I got an exception about an unresolvable circular dependency between my public class SecurityConfiguration extends KeycloakWebSecurityConfigurerAdapter and KeycloakSpringBootConfigResolver after I switched Spring Boot Web from Tomcat to Jetty (see https://stackoverflow.com/a/66297192/8534088).

The exception on Spring Boot app start looked like this:

org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfiguration': Unsatisfied dependency expressed through field 'keycloakConfigResolver'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'keycloakConfigResolver': Requested bean is currently in creation: Is there an unresolvable circular reference

To fix the unresolvable circular dependency, I changed

@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)

to

@ComponentScan(basePackageClasses = KeycloakSpringBootConfigResolver.class)

on my SecurityConfiguration class.

The initial configuration was taken from https://www.baeldung.com/spring-boot-keycloak#securityconfig.

like image 1
Dmitriy Popov Avatar answered Oct 06 '22 18:10

Dmitriy Popov