Account Linking

Need help with Account Linking

Info:
Backend is in NodeJS
Frontend is ReactNative
Keycloak v18

Requirement:

  1. Frontend fetches the linking URI genereted by backend
  2. Hits the URI to initiate account linking to external idp

Problem:
When hitting the URI generated from frontend with or without the access_token, we get the “not_logged_in” error

When we attach the cookies ( getting them from impersonation call on backend using service token ):
Keycloak_identity, Keycloak_identity_legacy, Keycloak_session, Keycloak_session_legacy,
we get a new error = “invalid_token”

( tested using postman for cross domain cookies )

We have tried multiple values for session Id i.g, session id from access token the user is using, session id from the retrieved cookie ( keycloak_identity)

Link to Keycloak Doc for Account Linking: Server Developer Guide

One of the code sample we have tried:

  const sessionState = await extractSessionStateFromRequest(req)
  const clientId = KEYCLOAK_ID // this is the client id being used for backend connectivity

  const nonce = randomUUID()
  const idp = "google-link"
  const input = nonce + sessionState + clientId + idp
  const hash = crypto.createHash("sha256").update(input).digest("base64");
  const base64HashedData = hash.split('+').join('-').split('/').join('_').split('=').join('')

  const url = new URL(`${KEYCLOAK_URL}/realms/${KEYCLOAK_REALM}/broker/${idp}/link`)
  url.searchParams.set("nonce", nonce)
  url.searchParams.set("hash", base64HashedData)
  url.searchParams.set("client_id", clientId)
  url.searchParams.set("redirect_uri", "some_url")

  apiOk(res, { url });

Thanks for reading it.
Any help is appreciated.

Have a nice day!

1 Like