How to force an oAuth token renewal (access-token + refresh token) with Spring boot keycloak adapter + spring security.?

Viewed 4486

I have a multi-tenant application (springboot keycloak adapter + spring security) secured by Keycloak. Given the multi-tenant nature of the project, I wrote a multi-client connector which works fine.

On the official Keycloak doc, it is recommended (for multi-tenant applications) to model each tenant as a new realm, but for me it works better to have multiple clients within the same same realm. This is due to following advantages:

  • Client scopes, groups and other configs can be shared
  • Users don't need to be duplicated on N different realms
  • SSO login works perfectly within same realm clients (by using bearer services +CORS)

So, everything works fine except for 1 thing, my initial SSO access_token (which is then shared across all bearer-only services by means of CORS) is kind of big (it shows all the resources - tenants - and its roles within each resource/tenant).

I'd like to limit the size of the access_token, by means of using "scopes" to restrict the roles in the token to only those meaningful to the tenant where I'm logged in at that time. For this, I'm manually firing a Request to the auth server (outside of the standard functionality provided by springboot/spring security) with the goal of manually overwriting whatever access-token exists within my app, with the new one generated by my extra request.

My "new" token request looks similar to this:

    SimpleKeycloakAccount currentUserAccount = (SimpleKeycloakAccount) auth.getDetails();
            String authServerUrl = currentUserAccount.getKeycloakSecurityContext().getDeployment().getAuthServerBaseUrl();
            String realm = currentUserAccount.getKeycloakSecurityContext().getDeployment().getRealm();
            String resource =  currentUserAccount.getKeycloakSecurityContext().getDeployment().getResourceName();
            String refreshToken = currentUserAccount.getKeycloakSecurityContext().getRefreshToken();
            String token = currentUserAccount.getKeycloakSecurityContext().getTokenString();
            
            
            Http http = new Http( new Configuration(authServerUrl, realm, resource,
                            currentUserAccount.getKeycloakSecurityContext().getDeployment().getResourceCredentials()
                           , null), 
                       (params, headers) -> {});
            
            String url = authServerUrl + "/realms/" + realm + "/protocol/openid-connect/token";
            
            AccessTokenResponse response = http.<AccessTokenResponse>post(url)
                .authentication()
                    .client()
                .form()
                    .param("grant_type", "refresh_token")
                    .param("refresh_token", refreshToken)
                    .param("client_id", resource)
                    .param("client_secret", "SOME_SECRET")
                    .param("scope", "SOME_SCOPE_TO_RESTRICT_ROLES")
                .response()
                    .json(AccessTokenResponse.class)
                .execute();

// :) -  response.getToken() and response.getRefreshToken(), contain new successfully generated tokens
            

My question is, how can I force my-app to change/reset the standard access-token & refresh_token obtained by the usual means, with these "custom created" tokens? or is that possible at all?

Thx for any feedback!

Further Information

To clarify more, lets analyze the behavior of a typical springboot/spring security project integrated with Keycloak:

  • You protect your endpoints with "roles" via configurations (either on the application.properties, or on the SecurityContext)
  • You know that this Spring application talks in the back channel with the Keycloak authorization server, that's how you become the access_token (But all this is a black box for the developer, you only know a Principal was created, a Security Context, Credentials; etc - everything happens behind the curtains)

Considering those 2 points above, imagine that you use an Http library to basically request a new token towards the auth server token endpoint like in the code above (yes filtered by scopes and everything). So the situation now is that though you have created a valid access_token (and refresh_token); since they were created "manually" by firing a request towards the token endpoint, this new token hasn't been "incorporated" to the application because No new Principal has been created, no new security context has been generated, etc. In other words, to the springboot application this new token is non-existent.

What I'm trying to accomplish is to tell sprinboot/spring security: "Hey pal, I know you didn't generate this token yourself, but please accept it and behave as if you'd have created it".

I hope this clarifies the intent of my question.

3 Answers

You can revoke a token using org.springframework.security.oauth2.provider.token.ConsumerTokenServices#revokeToken method.

On the Autorization Server:

@Resource(name="tokenServices")
ConsumerTokenServices tokenServices;

@RequestMapping(method = RequestMethod.POST, value = "/tokens/revoke/{tokenId:.*}")
@ResponseBody
public String revokeToken(@PathVariable String tokenId) {
    tokenServices.revokeToken(tokenId);
    return tokenId;
}

Of course, you'll have to secure this method since is a very sensitive one.

In the case that each tenant is a separate client you can just use keycloak's "Scope" mapping at each client. Just turn off Full Scope Allowed and your tokens will only contain the user's roles for that specific client (tenant).

"Scope Mappings" is a a non intuitive way of saying "Define what roles should go into the access token" :-)

When turned off the UI changes and you even can configure what other roles of other clients should additionally go into the access token.

Reducing scope mapping of a client

Just to give some closure to this question:

  1. No, there doesn't seem to be any elegant or intended way to force a manual token renewal by means of using springboot/spring security keycloak connector.

  2. The Javascript connector can do this trivially like this:

     // for creating your keycloak connector
     var keycloak = Keycloak({
                    url: 'http://localhost:8080/auth',
                    realm: '[YOUR_REALM]',
                    clientId: '[YOUR_CLIENT]'
                });
    
    
     // for login in (change scopes list to change access capabilities)
     var options = {
           scope: [EMPTY_STRING_SEPARATED_LIST_OF_SCOPES]  // <-- here specify valid scopes
         };
    
     keycloak.login(options); // <-- receive a new token with correctly processed scopes
    
  3. Given how easy it is to do this with the Keycloak client JS adapter, and how obscure it is to do this with the springboot/spring security adapter, it follows following: Security design seems intended to have 2 (Keycloak security) layers; the first is a front-facing public client (usually password protected), and the 2nd layer is composed of several bearer-only services which would ussually only accept acces-tokens. If for those bearer-only services you want to implement finner grained control via scopes, you achieve that trivially by using a javascript based Keycloak client (other connectors as explained won't deal nicely with the header modification necessary to deal with OAuth2 scopes).

Related