Keycloak is an open-source identity and access management solution that provides single sign-on (SSO) and multi-factor authentication capabilities. In this guide, we’ll walk through the steps to set up Keycloak on a virtual machine for testing authentication.
Step 1: Download and Install Keycloak
- Download the Keycloak distribution package:
wget https://github.com/keycloak/keycloak/releases/download/19.0.2/keycloak-19.0.2.tar.gz
- Extract the downloaded package and navigate to the Keycloak directory:
tar zxvf keycloak-19.0.2.tar.gz
cd keycloak-19.0.2
- Create a script to set up Keycloak admin credentials:
nano setAdmintest
Add the following content to the script:
#!/bin/bash
export KEYCLOAK_ADMIN=test
export KEYCLOAK_ADMIN_PASSWORD=test
Make the script executable and run it:
chmod 755 setAdmintest
./setAdmintest
- Configure Keycloak database settings:
nano conf/keycloak.conf
Update the database settings to use PostgreSQL:
db=postgres
db-username=test
db-password=test
db-url=jdbc:postgresql://localhost/takaexchange
hostname=debian-oauth
- Update the
/etc/hosts
file to map the hostname to localhost:
sudo nano /etc/hosts
Add the following line:
127.0.1.1 debian-oauth
- Start Keycloak in development mode:
./bin/kc.sh start-dev
Step 2: Configure Keycloak Realm and Client
- Update the
/etc/hosts
file on your local machine to map the virtual machine’s IP to the hostnamedebian-oauth
. - Access the Keycloak administration console in your browser by navigating to
http://debian-oauth:8080
. - Log in using the admin credentials (
test/test
). - Hover over “Master” and click “Add realm.” Enter “test-service” as the realm name and save.
- Click on “Clients” and add a new client named “test-service-client.” Save the client configuration.
- Click on “Scope” and assign the scope
test-service-client-dedicated
. - Navigate to “Users” and add a new user with the username “debian” and password “debian”.
- Assign the role mappings for the user:
- Realm Roles:
manage-users
,view-clients
,view-realm
,view-users
Step 3: Obtain Access Token
- Click on “Clients” and copy the “Secret” of the client “test-service-client”.
- Use cURL to obtain an access token:
curl -X POST https://auth.domain.com:8443/realms/test-service/protocol/openid-connect/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "client_id=test-service-client&grant_type=password&username=debian&password=debian&client_secret=<client_secret>"
- Send the request and obtain the access token.
Conclusion
Congratulations! You’ve successfully set up Keycloak on a virtual machine for testing authentication. Keycloak provides a robust solution for managing user identities and securing access to your applications. By following the steps outlined in this guide, you can test authentication workflows and integrate Keycloak into your development and testing environments with ease.