Generate Keycloak Access Tokens with Curl
I’ve been working more with Keycloak lately and I’m loving it. But one thing I wanted to do while testing is to generate access tokens easily. Today I wrote a small wrapper script and thought I should share.
1#!/bin/sh
2
3set -e
4
5HOST=`cat $1 | jq -r .host`
6REALM=`cat $1 | jq -r .realm`
7USERNAME=`cat $1 | jq -r .username`
8PASSWORD=`cat $1 | jq -r .password`
9CLIENTID=`cat $1 | jq -r .clientid`
10CLIENTSECRET=`cat $1 | jq -r .client_secret`
11
12curl -X POST \
13 https://$HOST/auth/realms/$REALM/protocol/openid-connect/token \
14 -H 'Content-Type: application/x-www-form-urlencoded' \
15 -d username=$USERNAME \
16 -d password=$PASSWORD \
17 -d grant_type=password \
18 -d client_id=$CLIENTID \
19 -d client_secret=$CLIENTSECRET
The script takes a single JSON file as input and uses the information inside to generate the token. The reason why I went with this approach rather than simple command line parameters is to enable me to quickly switch between Keycloak installations and realms.
Sample JSON file
1{
2 "host": "auth.localtest.me",
3 "realm": "realm_name",
4 "username": "user_name",
5 "password": "super_secret_password",
6 "clientid": "client_id",
7 "client_secret": "client_secret"
8}
localtest.me
is a cool service I discovered last night. *.localtest.me will resolve to localhost so you won’t have to fiddle with the hosts file for local development. The only downside to that is you will have to use a self signed certificate which requires modifying the script and adding the --insecure flag to curl.
To generate the token simply run
1./keycloak-curl.sh file.json
About Me
Dev gone Ops gone DevOps. Any views expressed on this blog are mine alone and do not necessarily reflect the views of my employer.
Recent Posts