UPDATE: Simple method with curl examples
- Install keycloak, add realm and client
- get the keys
curl https://$KEYCLOAK_URL/auth/realms/$REALM/protocol/openid-connect/certs
copy the first element of the keys
array and use it in the postgrest configuration for the jwt-secret
variable
- use
.preferred_username
as the value of role-claim-key
in postgrest configuration
Assuming you 've done the above you can test your installation:
- Get token
curl -X POST https://$KEYCLOAK_URL/auth/realms/$REALM/protocol/openid-connect/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "username=$USERNAME" \
-d "password=$PASSWORD" \
-d 'grant_type=password' \
-d "client_id=$CLIENT"
- Use the access_token element of the reply for your requests to postgrest
curl -H "Authorization: Bearer $ACCESS_TOKEN" $POSTGREST_URL/your_table
There are several ways to do it, I'll just describe one:
- Set up keycloak to pass the claims you want in the token. ( Probably you would want a claim of type
"role": "username"
)
- Get the key keycloak is using and pass it in the jwt-secret section of the postgrest configuration
- Set up a web server to communicate with keycloak and get the tokens.
- Pass the token to the browser
- Use the token to access postgrest
Details
- In keycloak admin console go to:
/#/realms/<realm name>/clients/<client id>/mappers
and set the claims you want
- In keycloak admin console at
#/realms/<realm name>/keys
you can get your rsa public key, translate it to jwk format and save it to the postgrest configuration. In order to translate it to jwk
- Translate it to pem format by enclosing it in
-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----
- Translate it to jwk format. A nice tool pem-jwk
There are infinite options. A node js example: https://github.com/keycloak/keycloak-nodejs-connect/tree/master/example that uses the keycloak-connect package
You can read the token at req.kauth.grant
and place it at a hidden field of the html you send to the browser
From the browser read the token and place it at the authentication header with the bearer prefix. If you use axios:
axios({
method: 'get',
url: 'your url',
headers: { 'authorization': `Bearer ${token}` }
})