Add tenant info to access token in spring-authorization-server

63 Views Asked by At

I want to have two tables: users and tenants. Each user might belong to many tenants and have different roles in each tenant. I want my /token endpoint to return an access token which will contain information about to which tenants the user belongs and what role the user has in each tenant. Somethings like this:

{
  "tenants": [
    {
      "name": "tenant1",
      "roles": [
        "ADMIN"
      ]
    },
    {
      "name": "tenant2",
      "roles": [
        "CUSTOMER"
      ]
    }
  ]
}

I found this example in the docs:

@Bean
public OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer() {
    return context -> {
        JwsHeader.Builder headers = context.getJwsHeader();
        JwtClaimsSet.Builder claims = context.getClaims();
        if (context.getTokenType().equals(OAuth2TokenType.ACCESS_TOKEN)) {
            // Customize headers/claims for access_token

        } else if (context.getTokenType().getValue().equals(OidcParameterNames.ID_TOKEN)) {
            // Customize headers/claims for id_token

        }
    };
}
  1. I should probably use the mentioned example to add these custom claims, but how can I know at this point which user is currently being authenticated? So that I could query the tenants' table and see where this user belongs.

  2. When my backend receives an access token from the UI, which includes two tenants, it will need to distinguish somehow to which tenant the call is being made. My UI app can attach a tenantId request header for every call along with the access token so I can distinguish the tenant. But I'm wondering if it wouldn't be easier and possible to pass some additional request header/parameter to the /token endpoint called tenantId so that the access token returns the role of the user only for the provided tenant? That way the access token will always contain only one tenant's details, even though the user belongs to more tenants, and then I will not have to send tenantId as a request header with every request.

0

There are 0 best solutions below