Logged in user in preferred_username, not in sub, configurable?

In a Spring Security OAuth2 project with Spring Boot and Keycloak with Authorization Code grant type I see some difference in the structure of the access token in regards where the username of the logged in user is put, in comparison with the access token from my earlier try with the Spring Security Authorization Server experimental project.

I thought OAuth2 is a standard, so at least some parts of the access token JSON must be the same.

Spring Security OAuth2 Authorization Server (experimental)
PAYLOAD:DATA
{
“sub”: “aadmin”,

}

Keycloak
PAYLOAD:DATA
{
“sub”: “95a3d678-75fa-4a4c-84d4-4d5df1facbb2”,
“preferred_username”: “aadmin”,

}

I don’t know which version is more close to the OAuth2 standard.
Is this on Keycloak side a configuration, so that the username of the logged in user is put into the preferred_username attribute? Can this be configured to be in the sub attribute?

I right now use only Keycloak, but to be more close to the OAuth2 standard, and also more flexible if someone in the project decides to switch the authorization server, I would like my code in the frontend and backend not to be modified much, if I have to obtain some information from the access token.

If I expect the username of the logged in user to be always in the sub attribute, my code just has to access that attribute. It would be cumbersome if it is dependent on the authorization server used, and everytime in a different attribute.

Keycloak is about OIDC, OIDC is using the OAuth2 flows.
OAuth2 doesn’t define a token format, OIDC does. OIDC uses JWT as token format.
The sub claim (defined by JWT spec) is not about the “username”, it’s about a unique identifier for the user, it’s not necessarily the username! In Keycloak, it’s the user ID.
You can map additional attributes from a user into the various tokens claims and user-info endpoint with token mappers.

Thanks for the quick answer.

So it means, that Keycloak for example puts the roles into the access token (realm_access > roles), but another authorization server might not put them at all into the access token or in a differently named attribute?

Does OIDC also define how roles are added into the access token? So to say, if I use another authorization server with OIDC functionality in the future, the roles must therefore be expected to be defined in the access token in realm_access > roles?

So to say your answer OAuth2 doesn’t define a token format, OIDC does I may find the token format definition of OIDC somewhere in the OIDC standard?

OIDC says nothing about roles. One AuthServer might put them into roles another AS into something different. Even if the claim name is the same, the structure of the data might differ.

For your reference: