Categorías
Keycloak

Request tokens from Keycloak using OIDC endpoints

Embark on a journey into the heart of Keycloak authentication, mastering token acquisition via OAuth 2.0 and OpenID Connect. From setting up the server to exploring grant types, this guide demystifies authentication, leaving you equipped to secure applications effortlessly.

Introduction

In the realm of secure authentication and authorization, OAuth 2.0 and OpenID Connect (OIDC) protocols play key roles. This post explores the essentials of obtaining tokens from a Keycloak 23.0.4 server using the OIDC endpoints.

We will use the various grant types (from Authorization Code to Client Credentials) to obtain the tokens, enhancing your understanding of securing applications with Keycloak. Embark on this concise journey into the heart of request tokens to amplify your grasp on authentication and authorization in the Keycloak environment.

Prepare your server

Install Keycloak

First of all, you will need to get a Keycloak server (either in a Docker container or on your PC). If you have the Keycloak server in your PC you will need to execute the following in the Keycloak folder to start the server:

bin/kc.[sh|bat] start-dev

Create a realm

Once the server is running we are ready to create a realm; we will call it «myrealm». In Keycloak, a realm is a distinct security area with its own user and application management settings.

Create a client

The following step will be creating a client from which we will perform the tokens requests. We will call it «myclient».

Note that in the Capability config area we must activate Client authentication. This defines the type of the OIDC client. When it’s ON, the OIDC type is set to confidential access type. When it’s OFF, it is set to public access type. We also need to activate Service accounts roles. As we will see soon, this allows you to authenticate this client to Keycloak and retrieve access token dedicated to this client. In terms of OAuth2 specification, this enables support of Client Credentials Grant for this client.

Get client credentials

In the next section, we will request tokens using the client’s credentials. Because of this, we will need to know the client id (myclient) and the client password. To obtain this password go to:

And you can click on the eye or copy button to get the credentials.

Create a user

The last configuration step will be creating a user.

In our case the user will have the username «alice», email «alice@alice.es».

Once the user is created we will need to set a credentials for it, this is, a password.

It is important to set the Temporary obtion to unchecked, because if enabled, the user would need to change the password on the first login.

Requesting the tokens

As you may know, Keycloak provides different kinds of tokens: Access, Refresh, and ID tokens (this post helped me to figure out the differences among them). Basicly, Access Tokens grant permission to access protected resources, Refresh Tokens enable token renewal without reauthentication, and ID token provide user identity information.

In Keycloak, these tokens can be requested in several ways; these «ways» are called grants. Each grant type offers a distinct approach to authentication and authorization, allowing developers to tailor de token acquisition process according to specific use cases and security needs.

We will walk through how to obtain these tokens using these different grants.

Postman collection

I have created a Postman collection containing all the request I have used during this post, you can download it here.

Note that, in order to execute the requests properly, you need to have the following Postman environment configured.

Note also that the variables kc_refresh_token, kc_access_token and kc_id_token are automatically assigned to the values received in the requests. This behavior is set in the Test section of every Postman request.

You can download the environment variables export file here or configure them manually.

Resource Owner Password Credential Grant

The Resource Owner Password Credential (ROPC) Grant simplifies authentication, involving the direct exchange of user-provided credentials for access tokens.

Endpoint: {{kc_server}}/realms/{{kc_realm}}/protocol/openid-connect/token
Method: POST
Body:

KeyDescription
client_idId of the Keycloak’s client
client_secretSecret of the Keycloak’s client
grant_typepassword
scopeopenid
usernameUser’s username
passwordUser’s password
Body of the Resource Owner Password Grant token request

If I send the request using Postman I get the following response.

As you can see, the response contains several keys in JSON format.

KeyDescription
access_tokenResponse’s Access Token
expires_inAccess Token’s expiration time (in seconds)
refresh_expires_inRefresh Token’s expiration time (in seconds)
refresh_tokenResponse’s Refresh Token
token_typeType of token, usually Bearer
id_tokenResponse’s ID Token
not-before-policyTimestamp that indicates the time before which the JWT must not be accepted for processing. More info here.
session_stateKeycloak’ session state
scopeopenid email profile
Token’s response JSON explained

Client Credentials Grant

The Client Credentials Grant enables secure access by allowing applications to directly request access tokens using their client credentials, streamlining authentication for machine-to-machine communication.

Endpoint: {{kc_server}}/realms/{{kc_realm}}/protocol/openid-connect/token
Method: POST
Body:

KeyDescription
client_idId of the Keycloak’s client
client_secretSecret of the Keycloak’s client
grant_typeclient_credentials
Body of the Client Credentials Grant token request

Refresh Token Grant

The Refresh Token Grant facilitates seamless token renewal, allowing applications to obtain fresh access tokens without requiring user reauthentication, enhancing the efficiency and security of long-running sessions.

Endpoint: {{kc_server}}/realms/{{kc_realm}}/protocol/openid-connect/token
Method: POST
Body:

KeyDescription
client_idId of the Keycloak’s client
client_secretSecret of the Keycloak’s client
grant_typerefresh_token
scopeopenid
refresh_tokenRefresh Token to obtain in a previous request
Body of the Client Credentials Grant token request

Authorization Code Grant

The Authorization Code Grant is a secure authentication process where clients obtain access tokens by exchanging an authorization code, optimizing user authentication for web applications while maintaining robust security measures.

In this case, the authorization code would come from the authorization server, this is, Keycloak. I will create a post showing a case study of this situation soon.

Endpoint: {{kc_server}}/realms/{{kc_realm}}/protocol/openid-connect/token
Method: POST
Body:

KeyDescription
client_idId of the Keycloak’s client
client_secretSecret of the Keycloak’s client
grant_typeauthorization_code
scopeopenid
codeAuthorization Code obtained from Keycloak
redirect_uriURI to redirect
Body of the Authorization Code Grant token request

Conclusion

In conclusion, we’ve navigated the crucial steps of securing applications with Keycloak, honing in on token acquisition using OAuth 2.0 and OpenID Connect. From setting up the Keycloak server and creating realms, clients, and users to exploring grant types like Resource Owner Password Credential, Client Credentials, Refresh Token, and a glimpse into Authorization Code Grant – we’ve covered it all. This guide is your go-to for understanding authentication and authorization in the Keycloak environment. Plus, I’ve got a Postman collection with all the requests for practical implementation – go ahead, download it and dive into a more secure application experience!

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *