In this blog we will generate Access Token and Refresh Token using KeyCloak. KeyCloak uses Role based access so every user must have a role attached to it. For this we will first create an app in KeyCloak, set up a user and attach it to a role.
Create an App in KeyCloak
- Log into KeyCloak with the admin user created in previous blog.
- Select realm at the top.
- Click on Clients and select Create.
- Provide client name and click Create.
- Next update the new client created above. Enter “Valid Redirect URIs” example “http://localhost:28080/*“. Leave other field as it is and click on save.
Create Role and User in KeyCloak
- Click on Roles in the left hand side menu.
- Click on Add Role button. Enter Role name and hit save.
- Click on Users.
- Click on Add User, fill up Username and hit save.
- Go to credentials tab and enter password and click save.
- Attach role to user. Click on Role Mappings tab in the users. Select role from Available Roles and click Add Selected.
Generating Access tokens using CURL and Postman
KeyCloak provides Restful services to generating and refreshing access tokens. Curl Command to generate access token:
curl --location --request POST 'http://localhost:28080/auth/realms/AWSRealm/protocol/openid-connect/token' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --data-urlencode 'client_id=tantra' \ --data-urlencode 'username=tantra-api' \ --data-urlencode 'password=admin' \ --data-urlencode 'grant_type=password'
Postman request json can be found here.