Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issuing "API keys" using Keycloak

My setup has three components:

  • A backend application (Python/Flask)
  • A frontend application (VueJS)
  • Keycloak

The frontend will use Keycloak to let users sign in and use the access tokens to authenticate requests to the backend. So far so good.

Now I want third party applications to be able to make authenticated requests against the backend and I am wondering how that can be realized using Keycloak? My idea is to issue a new set of credentials for each customer. Their application then talks to Keycloak to get access tokens. I can then use Keycloak to manage access control for all users of the API.

  • How would a 3rd party app be represented in Keycloak - client? user? ...?
  • Are there best practices for this kind of use case?
like image 942
Marco Lamina Avatar asked Sep 07 '18 23:09

Marco Lamina


1 Answers

I finally found a solution that works well and seems to be "the Keycloak way" to issue credentials to external applications. To create a new set of credentials, add a new Keycloak client and change the following settings:

  • Standard Flow Enabled: OFF
  • Direct Access Grants Enabled: OFF
  • Access Type: Confidential
  • Service Accounts Enabled: ON

The external application will use our newly created client's name as the client_id. The client_secret was generated automatically and can be found under the Credentials tab.

Granting Client Access to Your Services

If your Keycloak-protected services are configured to check the aud claim of incoming Bearer tokens, a second step is necessary. By default, the audience of the JWT tokens that Keycloak issues to your client will be set to your client's name, so they will be rejected by your services. You can use Client Scopes to modify that behavior:

  1. Create a new client scope
  2. Select "Audience Template"
  3. Select the service you'd like to grant your external applications access to and click "next"
  4. Add the scope to the client you just created (Client Scopes tab)

Keycloak will now add your service's name to the aud claim of all JWT tokens it issues to your new client. Check out the Keycloak documentation on Service Accounts for more details.

Exchanging Client Credentials for an Access Token

An external application can now use its credentials to obtain an access token from Keycloak's token endpoint:

POST {keycloak-url}/auth/realms/atlas/protocol/openid-connect/token

  • Set the Content-Type header to application/x-www-form-urlencoded
  • Authenticate the request with Basic Authentication, using your client id as the user and your client secret as the password
  • Set grant_type=client_credentials in the request body
like image 58
Marco Lamina Avatar answered Sep 18 '22 20:09

Marco Lamina