Lab M04P05
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
- Open Keycloak administration web console http://localhost:8090 and login as user/bitnami.
- Create new realm with name demo and select it.
- Configure client for postman with name postman
- Add some test User
- Define Realm Roles and assign them to User as needed
Lab steps
-
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.
-
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.
-
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(); } -
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. -
The access control definitions can be configured using Java code in SecurityConfig.