Skip to content

r&d keycloak

AppliNH edited this page Aug 23, 2020 · 4 revisions

Keycloak

Keycloak is an openSource identity and access management tool.

POC IS HERE !

Run

Using docker:

docker run -p 8080:8080 -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin quay.io/keycloak/keycloak:11.0.1

How does it work (briefly)

Getting started official doc

Keycloak works through "realms". A realm is an isolated group of applications and users.

So, in brief, you:

  • Create a realm
  • Create some users
  • Create an application, or client, which registers the app that will use the realm.

You also can import a realm (example file here). You'd then add this to the docker run command:

-e KEYCLOAK_IMPORT=/tmp/example-realm.json -v /your-host-dir/example-realm.json:/tmp/example-realm.json

The KEYCLOAK_IMPORT env variable points to the file inside of the running container.

docker run -p 8080:8080 -e KEYCLOAK_USER=admin \ 
-e KEYCLOAK_PASSWORD=admin \ 
-e KEYCLOAK_IMPORT=/tmp/example-realm.json \ 
-v /Users/primitivo/Documents/Projects/Primitivo/OWLY/Owly.wiki/keycloak-assets/example-realm.json:/tmp/example-realm.json  \ 
quay.io/keycloak/keycloak:11.0.1

The keycloak server also exposes a REST API you can use to login and generate JWT Tokens.

Tutorial here

Management

You can create an admin user on startup with:

  • env variables:
    • KEYCLOAK_USER=<USERNAME>
    • KEYCLOAK_PASSWORD=<PASSWORD>

You can create a regular account by executing:

/opt/jboss/keycloak/bin/add-user-keycloak.sh -u <USERNAME> -p <PASSWORD>

Of course you can do a lot of stuff like that using the SDK or the REST API.

Client REST API: request examples

As said above, the keycloak server exposes a REST API that can be consumed by the client.

I recommend following this tutorial.

Sign in

Method URL
POST http://localhost:8080/auth/realms/``/protocol/openid-connect/token

Payload

Be careful ! This content-type is application/x-www-form-urlencoded and not application/json !

client_id=<client_id>
grant_type=password
client_secret=<client_secret>
scope=openid
username=<username>
password=<password>

Response

{
    "access_token": "",
    "expires_in": 3600,
    "refresh_expires_in": 1800,
    "refresh_token": "",
    "token_type": "bearer",
    "id_token": "",
    "not-before-policy": 0,
    "session_state": "",
    "scope": "openid email profile"
}

Sign-Up / User registration

User registration from keycloak interface

You can also call the REST API using the AccessToken of an admin user account:

Method URL
POST http://localhost:8080/auth/admin/realms/``/users

Headers

Name Value
Content-Type application/json
Authorization Bearer <ACCESS_TOKEN>

Payload

{
    "firstName":"Sergey",
    "lastName":"Kargopolov", 
    "email":"test@test.com", 
    "enabled":"true",
    "username":"app-user"}

Go SDK

It's way easier to use this SDK tbh.

Gocloak

Clone this wiki locally