Skip to content

Lab M09P01

The Spring Security framework supports of the latest standards of the web applications security. This lab introduces you to OAuth2 and OpenID Connect standards in context of simple backend which plays role of OAuth2 Resource Server. This lab requires running Keycloak IAM server, which plays role of OAuth2 Authorization Server. Please check the docker-compose folder and start Keycloak in container using docker compose up -d command from this folder. You need docker environment on your notebook.

Keycloak configuration

  1. Open Keycloak administration web console http://localhost:8090 and login as user/bitnami.
  2. Create new realm with name demo and select it.
  3. Configure client for postman with name postman
  4. Add some test User
  5. Define Realm Roles and assign them to User as needed

Lab steps

  1. To add the OAuth2 Resource Server capability to your Spring Boot application is simple. First you need to configure build script. Check the implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server' dependency in build.gradle file.

  2. Then you need to configure Spring application to talk with Keycloak. Open the application.properties and add spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8090/realms/demo property.

  3. The KeycloakJwtAuthenticationConverter implements the GrantedAuthority adaptation to Access Token format issued by Keycloak server. In other words Roles included in Access Token issued for User are converted into format which Spring Security understands. The converter is used in SecurityConfig configuration class:

      @Bean
      public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    
         http.authorizeHttpRequests(authorize -> authorize
               .anyRequest().authenticated()
               ).oauth2ResourceServer(oauth2 ->
               oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(new KeycloakJwtAuthenticationConverter()))
         );
       return http.build();
     }
    
  4. Now, add declarative method access control into the ApiController class. Spring defines @PreAuthorize annotation with takes argument in form of SpEL expression, which defines required access grants. You have the following requirements:

    • helloWorld() is accessible only for Users with role USER or ADMIN
    • adminHelloWorld() is accessible only for Users with role ADMIN

    Try to implement above requirements.

    Hint: You can use hasRole() and logical operators in expression in @PreAuthorize annotation.

  5. The access control definitions can be configured using Java code in SecurityConfig.