Akka Jaworek
Akka Jaworek

Reputation: 2120

Microservice authentication with Keycloak

I'm trying to authenticate one microservice request in another microservice, but I'm failing to find any examples showing how to configure the client in keycloak and how to configure spring security. This is the architecture I'm trying to archive:

enter image description here

I have already managed to get user authorization working and secure microservice A, and now i'm trying to authorize requests from microservice B, but i'm not sure how to do it, whether should I create a dedicated user in keycloak for microservice B, or client in realm, or some other technical account? Is it done by some api key or should Microservice B request access token in the similar way the user does?

My idea is to create a client in Keycloak for microservice B, request an access token from Keycloak and attach it to every request sent to microservice A.

Is this the correct approach?

Is there some library addressing this case?

I could not find any example of such communication with spring, are you aware of any repositories with such example?

Upvotes: 2

Views: 2073

Answers (1)

Evil_skunk
Evil_skunk

Reputation: 3382

As far as I understood, your Frontend access to MS-A is done with different user accounts (logins). But for MS-B accessing MS-A it's okay when MS-B always use the same account (MS-B Service Account)?

In this scenario I would create a second client for this backend authentication, let's call it backend-client with the following options:

OIDC, confidential, enable Direct Access Grants and Service Accounts, disable standard Flow

MS-B can now obtain a Access Token via a simple Request to Keycloak

 curl --request POST \
        --url https://keycloak/auth/realms/%realm_name%/protocol/openid-connect/token \
        --header 'Accept: */*' \
        --header 'Content-Type: application/x-www-form-urlencoded' \
        --data 'client_id=backend-client&client_secret=%client_secret%&grant_type=client_credentials'

(No User+PW is required, so keep client_secret really safe)

The access token now needs to be used for all Requests from MS-B to MS-A (Authentication: Bearer %Access-Token% Header)

I'm unaware of any spring implementations / adapters, but I'm pretty sure if you search for Direct Access Grants you will find a proper solution

Upvotes: 1

Related Questions