Spring-Boot-Angular-Keycloak
1. Introduction
In this tutorial I will show you how to secure a distributed application (front: Angular, back: Spring boot) with Oauth2/OIDC (JWT) Keycloak.
To project our example on the oauth2 protocol, here is the role of each application.
To simplify, I created a single microservice with one rest-conroller with 2 Gets methods (/hello_user, /hello_admin).
the purpose of the tutorial is:
- when the user wants open the page User or Admin, the provider Angular-Keycloak redirects it to login page of keycloak
- after sign in the keycloak redirect user to front-app
- finally the user is redirected to the requested page to see the hello admin or hello user message depending on the profile
I assume you already know the configuration of realms, clients and users in Keycloak
Below are the main steps to implement your project
2. what’s Oauth2/OIDC?
before starting, I would like to remind you of the principle of the Oauth2 and OIDC protocol
A- Oauth2 :
- Protocol and framework of authorization delegation
- has tree parts
a) Client: Angular application
b) Resource: Spring boot application
c) Authorization server: Keycloak
B- OIDC:
- Protocol of identity management
- The ID TOKEN use (JWT)
a)Access Token
b)Refresh Token
- Google is OIDC because generates JWT after authentication and code verify
- GitHub is not OIDC because does not generate a JWT Token
3. Tutorial
A- Environment:
In this tuto i used:#Windows 11, #Docker Desktop, #VsCode latest version,#open-jdk-17, #maven 3.9, #nodejs latest version,#Angular17
B- Custom Spring project
1. Create a new spring project (spring-angular-oauth2-jwt) from https://start.spring.io/ choose maven in Project, Java in Langage, Packaging Java and version Java 17
2. Add Web in the dependencies
3. Download project in your machine
4. Create rest-controller HelloWorldApi in the package rest of your project
5. Create 2 Get methods HelloWorldUser and HelloWorldAdmin
6. I add Personne DTO to simplify the Data Binding in Angular Project
C- Create Angular Project
for this example i created the project angular in a subfolder of spring-angular-oauth2-jwt
1. install angular : npm install @angular/cli
2. create project angular : .\node_modules\.bin\ng.cmd new angular-front --directory ./ --no-standalone
3. create component user : ng.cmd g c user
4. create component admin : ng.cmd g c admin
5. add bootstrap style: npm i bootstrap bootstrap-icons
6. for using style and javascript bootstrap 5 with our project(angular.json) we add style bootstrap in balise style and script bootstrap in scripts
"styles": [
"src/styles.css", "node_modules/bootstrap/dist/css/bootstrap.min.css"
],
Recommended by LinkedIn
"scripts": [ "node_modules/bootstrap/dist/js/bootstrap.bundle.js"
]
7. in the file style.css we can import icons
/* You can add global styles to this file, and also import other style files */
@import "bootstrap-icons/font/bootstrap-icons.min.css";
8. for template we used a navbar from bootstrap https://getbootstrap.com/docs/5.0/components/navbar/
9. we pasted this code in app.component.html and we added <router-outlet></router-outlet>
10. in the app.component.html we create a menu of application, here we have (index, User and Admin)
11. in the app-routing.module.ts we create the rootes of application (index, user, admin)
12. add HttpClientModule in imports of app.module.ts
D- Call Rest-Controller without security from Angular Project
1. Go to user.component.ts/admin.component.ts and call hello user by HttpClient in OnInit() for calling [/hello_user,/hello_admin]
2. assign value to string variable helloUser/helloAdmin
3. display the string variable in user.component.html/admin.component.html
E- Start and configure Keycloak/Postgresql with DockerCompose
1. Create a new file docker-compose in spring-angular-oauth2-jwt
2. we need postgres image, volume for persisting data and environment to customize schema, user and password for keycloak
3. we need keycloak image, environment for define connexion to postgres, useradmin/passwordadmin to connect to keycloak admin, entrypoint to start keycloak, internal/external ports and depends-on for starting order
4. we start docker-compose with command : docker compose up
5. after starting keycloak we created:
* a new realm with name ahal
* a new client with name angular-front-client
. do not active authentication because we will be using the grant_type code_flow
. set Valid redirect URIs with value : [localhost:4200/*]
* 2 users (user,admin)
* 2 roles (USER,ADMIN)
* affect the role USER to user, and ADMIN to admin
F- Add Angular-Keycloak adapter
Now we can add the keycloak provider to ensure redirections, return jwt and secure menus between keycloak and frontal application.
all detail is the link: https://www.npmjs.com/package/keycloak-angular
1. create the guard configuration extends KeycloakAuthGuard for forcing the user to log in if currently unauthenticated.
2. authorize the user according to their roles to access a route
3. in the app.component.ts load user profil if currently is authenticated
4. add login/logout method for manage sessions in keycloak
5. add html code in app.component.html for display connected user, button login and button logout
6. add roles and guard to access a route in app-routines.module.ts
G- Secure spring boot application
to secure the spring application we need to:
1. add OAuth2 Resource Server to pom.xml
2. add the security configuration for :
- Enable web security
- forbidden all requests unauthenticated
- Enable Method Security for verify role before executing service
3. define this microservice as a resource
4. create a jwt converter for extracting roles
5. update application.yml:
- add security oauth2 resourceserver for connection to realm and get public key for verify signature
6. Add @PreAutorize for role authorization for services
7. Authorize All origins with CrossOrigin for this example
4. Conclusion
All these stages are implemented in this project on github https://github.com/ahalshaba/spring-angular-oauth2-jwt , you can download the sources and test it.
Do you have an example but using an nginx as a reverse proxy, the SSL certificate is only in the nginx, but the microservices and the keycloak are in edge mode
Hi sir, how can be configure spring boot application with keycloak SAML protocol ?
Merciiii
Bravo!