How ExternalIdentityId works with Keycloak

Keycloak authenticates the user and issues a JWT containing a sub claim, which uniquely identifies the user in Keycloak.

After ASP.NET Core validates the JWT, the application extracts the sub claim and searches PostgreSQL for a user whose ExternalIdentityId matches it.

  • If the user exists: return the local User.Id.
  • If the user doesn't exist: create a new local user record, store the Keycloak sub as ExternalIdentityId, and return the newly generated local User.Id.

The flow, step by step

JWT sub abc-123-… from Keycloak ASP.NET Core validates the JWT reads sub Users table ExternalIdentityId == sub found? create local User Id = Guid.NewGuid() ExternalIdentityId = sub return local User.Id no yes first sign-in only every request after
Fig. 01  ·  From a Keycloak sub to a local User.Id
Walkthrough

Keycloak issues a JWT

The JWT payload contains something like:

{
  "sub": "abc-123-keycloak-id",
  "email": "[email protected]",
  "aud": "finance-api"
}

The sub value is the user's unique Keycloak identifier.