Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keycloak - How to request a token with a custom lifespan?

Context: We are using Keycloak to secure our APIs by usually passing tokens through Authorization Headers. However, these APIs also allow users to download files (for instance: https://api.service.io/users.xlsx).

To use these "download endpoints", our web client applications pass users' token via query strings. (e.g. https://api.service.io/users.xlsx?accessToken=${bearerToken})).

Problem: Passing tokens via query string has several security flaws (browser history, ...). Therefore we would like to pass a very short-lived token (e.g. lifespan of 15sec) instead of the normal one (lifespan of 300sec by default).

Question: How could we request a different token from Keycloak API (for instance, /realms/#{realm_id}/protocol/openid-connect/token) by:

  • providing the normal access token (not credentials);
  • and specifying a different lifespan ?
like image 422
Lorent Lempereur Avatar asked Jan 17 '18 10:01

Lorent Lempereur


People also ask

How do I specify refresh tokens lifespan in Keycloak?

The refresh tokens lifespan is defined by the "Client Session Max" parameter in the "Tokens" tab of the Realm settings. It can also be overridden on individual clients level under the "Advanced Settings" menu of the client settings page. The maximum time before a refresh token is expired and invalidated.

How do I change my Keycloak token expiration?

Log in to the Keycloak administration panel. Select the required Realm according to the brand ID. Go to Realm Settings > Tokens. Set the expiration period in the Access Token Lifespan field.

How do I add a custom claim to a Keycloak?

In your realm, select your client. For that client, go the 'Mappers' option and then click on 'Create'. You can have the mapper type as 'User Attribute' and select the option(s) to add the attribute to ID token, access token and userinfo. The attribute added here should exist on the user.

How do you get a token Keycloak?

Navigate to the Postman Authorization tab of your request. From the Type dropdown menu, select OAuth 2.0: Click on the Get New Access Token button that will open a dialog box for configuring the identity server (Keycloak in our case).


1 Answers

After reading Keycloak's source code, it appears this is not possible (version 3.4.2.Final) to ask for a specific lifespan at runtime.

However, I developed a Keycloak Custom REST endpoint to do that. https://github.com/looorent/keycloak-configurable-token-api

When this JAR file is deployed in Keycloak, you can ask for a given lifespan at runtime. For example: $ curl -X POST -d '{ "tokenLifespanInSeconds": 20}' -H "Content-Type: application/json" -H "Authorization: Bearer <user-access-token>" http://auth.service.io/auth/realms/a-realm/configurable-token

like image 155
Lorent Lempereur Avatar answered Oct 19 '22 07:10

Lorent Lempereur