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:
- Create a new client scope
- Select "Audience Template"
- Select the service you'd like to grant your external applications access to and click "next"
- 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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…