This guide provides steps for setting up Role-Based Access Control (RBAC) in Keycloak, building and running a Spring Boot 3.3.5 application, and testing APIs using curl
commands. It includes
configuration for user and admin roles.
- Java 17 or higher
- Spring-boot 3.3.4 or higher
- Keycloak 20 or higher
- Download and install Keycloak from the official Keycloak website.
- Start the Keycloak server:
./bin/kc.sh start-dev
- Open the Keycloak admin console at http://localhost:8080/admin and log in with your admin credentials.
-
Create a Realm:
- In the admin console, go to the "Create Realm" section and name your realm, e.g.,
my-app-realm
.
- In the admin console, go to the "Create Realm" section and name your realm, e.g.,
-
Create a Client:
- Under your new realm, navigate to Clients and create a new client named
my-app-client
. - Set Access Type to
confidential
.
- Under your new realm, navigate to Clients and create a new client named
-
Define Roles:
- Under Roles, create the following roles:
user
admin
- Under Roles, create the following roles:
-
Create a Test User:
- Go to Users and add a new user with roles.
- Assign Roles under the Role Mappings tab:
- Assign the
user
role to a standard user. - Assign both
user
andadmin
roles to an admin user.
- Assign the
To build the application, use the following Gradle command:
./gradlew build
This will compile the code and create a .jar
file in the build/libs
directory.
To run the application, use:
./gradlew bootRun
Alternatively, if running as a .jar
, use:
java -jar build/libs/your-app-name.jar
To authenticate, first obtain a token for a test user:
curl -X POST "http://localhost:8080/realms/my-app-realm/protocol/openid-connect/token" -H "Content-Type: application/x-www-form-urlencoded" -d "grant_type=password" -d "client_id=my-app-client" -d "client_secret=YOUR_CLIENT_SECRET" -d "username=YOUR_USERNAME" -d "password=YOUR_PASSWORD"
Replace:
YOUR_CLIENT_SECRET
with the client secret from Keycloak.YOUR_USERNAME
andYOUR_PASSWORD
with the credentials of the user in Keycloak.
Copy the access_token
from the response to use in the following API requests.
curl -X GET "http://localhost:8080/api/v1/students" -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
curl -X GET "http://localhost:8080/api/v1/students/{id}" -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Replace {id}
with the student ID you want to retrieve.
curl -X DELETE "http://localhost:8080/api/v1/students/{id}" -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
Replace {id}
with the student ID to delete.
With this setup, you should be able to test different API endpoints with role-based access controls configured in Keycloak and enforced in the Spring Boot application.