Securing an Angular and Spring Boot Application with Keycloak
Spring Boot is a open-source tool which uses Java-based frameworks for building web applications.
In this article we'll be using Keycloak to secure an Angular application and access secured resources from a Spring Boot Web application.
If you just want to skip to the code, visit the Phase Two Spring Boot example. We are also building Keycloak examples for other frameworks.
Setting up a Spring Boot project
In order to setup a Spring Boot project, a JDK version must be chosen. As of the time of writing, to be inline with the latest changes from Keycloak 24, the Java 17 baseline will be used. Other JDK versions can also be used for developing the resource server according to the preference of the developer.
Starting with Spring Boot 2.x the Keycloak client adapters were deprecated. In Spring Boot 3.x we will use native functionalities of the spring-boot-oauth2-resource-server to be able to configure the application security context.
Quick Start
To get this project up and running locally on your computer you can clone the Phase Two Spring Boot example or follow the instructions below to generate a project from scratch.
-
Set up the Spring Boot project.
To kickstart a project, we will use (and recommend) using the Spring Boot Initializr, a Web-based tool that provides a simple UI to generate the project.
Provide the following values to spring initializr for the project metadata:
Group: com.example
Artifact: spring-boot-keycloak
Name: spring-boot-keycloak
Description: Demo project for Spring Boot
Package name: com.example.spring-boot-keycloak
-
Add the required dependencies in spring initializr.
For the purpose of this project we will add the following dependencies:
- Oauth2 Resource Server
- Spring Web
- Spring Security
This will result in the following lines within
build.gradle.implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'Generate the project with those settings. Open the .zip in your preferred text editor.
-
Setup JDK 17 for the project. Follow instructions on the JDK setup page.
Setting up a Keycloak Instance
Before customizing the Spring Boot app, we need to set up and configure our Keycloak instance.
Instructions
If you already have a functioning Keycloak instance, you can skip to the next section.
Rather than trying to set up a "from scratch" instance of Keycloak, we're going to short-circuit that process by leveraging a free Phase Two Starter instance. The Starter provides a free hosted instance of Phase Two's enhanced Keycloak ready for light production use cases.
-
Visit the sign-up page.
-
Enter an email, use a Github account, or use an existing Google account to register.

-
Follow the register steps. This will include a sign-in link being sent to your email. Use that for password-less login.

-
After creating an account, a realm is automatically created for you with all of the Phase Two enhancements. You need to create a Deployment in the Shared Phase Two infrastructure in order to gain access to the realm. Without a deployment created, the Create Shared Deployment modal will automatically pop up.
-
Create a Shared Deployment by providing a region (pick something close to your existing infrastructure), a name for the deployment, and selecting the default organization that was created for you upon account creation. Hit "Confirm" when ready. Standby while our robots get to work generating your deployment. This can take a few seconds.

-
After the deployment is created and active, you can access the Keycloak Admin console by clicking "Open Console" for that deployment. Open it now to see the console.

At this point, move on to the next step in the tutorial. We'll be coming back to the Admin Console when its time to start connecting our App to the Keycloak instance.
Setting up an OIDC Client
Instructions
We need to create a OpenID Connect Client in Keycloak for the app to communicate with. Keycloak's docs provide steps for how to create an OIDC client and all the various configurations that can be introduced. Follow the steps below to create a client and get the right information necessary for app configuration.
-
Open the Admin UI by clicking Open Console in the Phase Two Dashboard.
-
Click Clients in the menu.
-
Click Create client.
-
Leave Client type set to OpenID Connect.
-
Enter a Client ID. This ID is an alphanumeric string that is used in OIDC requests and in the Keycloak database to identify the client.
-
Supply a Name for the client.
-
Click Next.

-
Under the Capability Config section, leave the defaults as selected. This can be configured further later.
- Client authentication to On.
- Authorization to Off.
- Standard flow checked. Direct access grants checked. All other items unchecked.

Click Next.
-
Under Login settings we need to add a redirect URI and Web origin in order. Assuming you are using the example applicaiton:
Valid redirect URI (allows redirect back to application)
http://localhost:3000/*Web origins (allows for Token auth call)
http://localhost:3000URI and Origin Details
The choice of
localhostis arbitrary. If you are using an example application running locally, this will apply. If you are using an app that you actually have deployed somewhere, then you will need to substitute the appropriate URI for that. -
Click Save

OIDC Config
We will need values to configure our application. To get these values follow the instructions below.
-
Click Clients in the menu.
-
Find the Client you just created and click on it. In the top right click the Action dropdown and select Download adapter config.
-
Select Keycloak OIDC JSON in the format option. The details section will populate with the details we will need.
- Note the
realm,auth-server-url, andresourcevalues.

- Note the
-
You also need to copy the Client secret in the Credential tab for the client to use. Once on the Credential tab, click the copy button to copy the key to your clipboard. Save the key somewhere for use later in this tutorial

Adding a Non-Admin User
Instructions
It is bad practice to use your Admin user to sign in to an Application.
Since we do not want to use our Admin user for signing into the app we will build, we need to add a another non-admin user.
- Open the Admin UI by clicking Open Console in the Phase Two Dashboard.
- Click Users in the menu.
- Click Add user.
- Fill out the information for Email, First name, and Last name. Click Create.
- We will now set the password for this user manually. Click Credentials (tab) and click Set Password. Provide a password for this user. For our use case, as a tutorial, you can leave "Temporary" set to "Off".
- Click Save and confirm the password by clicking Save password
Install and configure Spring Boot
Now that we've setup and configured Keycloak using Phase Two and cloned or created our Spring Boot application template, we will need to configure the project to leverage the capabilities provided by Keycloak.
-
Configure application settings
Update your
application.yamlconfiguration file with the Keycloak security configuration (it's possible your download includes aapplication.propertiesfile instead).spring:
application:
name: spring-boot-keycloak
security:
oauth2:
resourceserver:
jwt:
issuer-uri: $http-keycloak-url/auth/realms/$your-realm
jwk-set-uri: ${spring.security.oauth2.resourceserver.jwt.issuer-uri}/protocol/openid-connect/certsReplace
$http-keycloak-urlwith the Keycloak URL from the Phase Two hosted Keycloak instance.$your-realmwith the Keycloak realm created earlier in this tutorial.
If you are using the local Keycloak instance from the cloned example, use the local address for
$http-keycloak-url.The below Java code omits any imports, reference our example for necessary imports or use your text editor to assist with populating the imports.
-
Configure Spring Boot resource server
Under
src.main.java.com.springbootkeycloakcreate a new package,config, and create a classSecurityConfig.java. In this class, add theHttpSecuritysettings:@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
private final JwtClaimsConverter jwtAuthConverter;
public SecurityConfig(JwtClaimsConverter jwtAuthConverter) {
this.jwtAuthConverter = jwtAuthConverter;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(authz ->
authz
.requestMatchers("/api/**")
.authenticated()
);
http.oauth2ResourceServer(oauth2ResourceServer ->
oauth2ResourceServer.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthConverter))
);
http.csrf(AbstractHttpConfigurer::disable);
http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
return http.build();
}
}This configuration will make the Spring Boot act as an OAuth2 Resource Server's with JWT authentication. This configuration is part of the functionality provided by the
spring-boot-starter-oauth2-resource-serverdependency. Read more about it's configuration here. -
Add JWT token convert configuration
In the same
configpackage, create another class,JwtClaimsConverter.java. Add a converter for extracting the security context attributes from theaccess_tokenreceived from Keycloak.@Component
public class JwtClaimsConverter implements Converter<Jwt, AbstractAuthenticationToken> {
@Override
public AbstractAuthenticationToken convert(Jwt jwt) {
var authorities = extractRealmRoles(jwt);
return new JwtAuthenticationToken(jwt, authorities, getPrincipalFromClaim(jwt));
}
private String getPrincipalFromClaim(Jwt jwt) {
var claimName = "preferred_username";
return jwt.getClaim(claimName);
}
private Collection<GrantedAuthority> extractRealmRoles(Jwt jwt) {
Map<String, Object> resource = jwt.getClaim("realm_access");
Collection<String> roles;
if (resource == null
|| (roles = (Collection<String>) resource.get("roles")) == null) {
return Set.of();
}
return roles.stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role))
.collect(Collectors.toSet());
}
}The provided example uses the
preferred_usernameclaim for populating the principal of the security context and therealm_access.rolesto populate the authorities.This configuration is part of the functionality provided by the
spring-boot-starter-oauth2-resource-serverdependency. Read more about it's configuration here. -
Create the secured API resources:
In
src.main.java.com.springbootkeycloakcreate a new package,web, and create a new classTestController.java.To test the security integration two resource endpoints are defined:
/api/test/anonymous/api/test/user
Implemented with this code:
@RestController
@RequestMapping("/api/test")
public class TestController {
@RequestMapping(value = "/anonymous", method = RequestMethod.GET)
public ResponseEntity<String> getAnonymous() {
return ResponseEntity.ok("Hello Anonymous");
}
@PreAuthorize("hasRole('ROLE_user')")
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ResponseEntity<String> getUser()
{
return ResponseEntity.ok("Hello Secured with user role.");
}
}Because both endpoints have the prefix
/apithey will require a secure context in order to access them. Furthermore, the/api/test/userendpoint is secured using a predefined authorityROLE_user. This is a Realm role that can be created and applied to your example user from earlier in this tutorial.This logic can be used to extend access and authorization to any part of the application.
Start the application running with
./gradlew bootRun.
Testing the secured endpoints
The secured endpoints can be tested using curl with the Authorization header. The Authorization header must contain the access_token.
curl --location 'http://localhost:8080/api/test/anonymous' \
--header 'Authorization: Bearer {{$access_token}}'
curl --location 'http://localhost:8080/api/test/user' \
--header 'Authorization: Bearer {{$access_token}}'
To generate an access token, you can use the openid-connect/token endpoint from Keycloak.
curl -X POST \
--location "https://$http-keycloak-url/auth/realms/$keycloak-realm/protocol/openid-connect/token" \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'username=$test-user&password=$password&grant_type=password&client_id=$client-name&client_secret=$client-secret'
Substitute the values from your Keycloak instance and test user for $http-keycloak-url, $keycloak-realm, $test-user, $password, $client-name, and $client-secret.
In the returned HTTP response, the access_token will be present. Use this token to test the secured endpoints in the example curl's above.
At this point, your Spring Boot application is secured with Keycloak, but there is no "Frontend" to the application. In the next section, we will add an Angular SPA to demonstrate sign-in with Keycloak.