spring-security: `Authentication` in the security context is not updated during the refresh token flow

Describe the bug Apparently, neither the ID token nor the userinfo are updated during the refresh token flow in Spring clients with oauth2Login. This has at least two consequences:

  • the principal (OidcUser or OAuth2User) might contain outdated data
  • in case of an RP-Initiated Logout, the OidcClientInitiated(Server)LogoutSuccessHandler might build a redirection URI to the authorization server end_session_endpoint with an expired or outdated ID token, in which case the second part of the logout fails and the user session on the OpenID Provider might not be ended.

Additional context about ID tokens ID tokens are JWTs and, as with all JWTs, they expire.

ID tokens can be refreshed.

During RP-Initiated Logout, OpenID Providers SHOULD (not MUST) accept ID tokens even when the exp time has passed. This means that some OPs might not accept expired tokens and that clients would better do their best to send valid tokens.

Also, aside from expiration considerations, most OPs refreshing ID tokens accept only the last token they issued for a client. So when a new ID token is returned as part of a refresh token flow, the client should use this last issued ID token to build the RP-Initiated Logout location URI.

Last, I know no constraint in the specs about the different tokens relative lifespans. As a consequence, it seems possible that an ID token expires before the access one. And as far as I understood the source, the RefreshToken(Reactive)OAuth2AuthorizedClientProvider refreshes tokens only if the access token expired which leaves room for expired ID token in the security context.

To Reproduce Using an authorization server refreshing ID token as part of the refresh token flow (Keyckloak is one, and, according to the Stackoverflow question linked below, Spring Authorization Server seems to be another):

  • login to an oauth2Client configured with oauth2Login and RP-Initated Logout
  • wait until the access token is expired
  • have refresh token flow executed. Using the (Reactive)OAuth2AuthorizedClientManager to retrieve the access token - like Spring Cloud Gateway TokenRelay= filter does - is enough.
  • initiate RP-Initiated Logout (send a POST request to the /logout endpoint)

Expected behavior

  • tokens should be refreshed if either the access or the ID token has expired (or will before the clockSkew)
  • if the security context contains an ID token (the principal is an OidcUser) and if the refresh token response contains an ID token, then the ID token in the security context should be updated
  • redirection to the authorization server end_session_endpoint should be built with the last issued ID token

The OidcClientInitiated(Server)LogoutSuccessHandler currently uses the (Reactive)ClientRegistrationRepository which doesn’t trigger the refresh token flow in case of expired tokens. Shouldn’t it use the (Reactive)OAuth2AuthorizedClientManager instead?

Some StackOverflow questions related to this issue:

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 10
  • Comments: 24 (20 by maintainers)

Most upvoted comments

Hey folks, sorry for the delay, it has taken some time to make progress on this issue (which I suspected would be the case). I have updated the PR #16589 based on work by @yhao3 with changes to fully capture this idea.

There are two pairs of events and listeners:

The first listener (OidcAuthorizedClientRefreshedEventListener) captures the “refresh” of an OAuth2AuthorizedClient and the associated OAuth2AccessTokenResponse by listening for the event OAuth2AuthorizedClientRefreshedEvent. This listener processes the response and determines if an OidcUser needs to be refreshed by looking for an id_token. If found, it publishes another event, OidcUserRefreshedEvent.

The second listener (OidcUserRefreshedEventListener) simply listens for OidcUserRefreshedEvent and updates the SecurityContext.

The reason there are two events is that it is nice to keep separate the logic of creating an updated Authentication (for this specific scenario) and actually updating the SecurityContext. I feel that updating of a SecurityContext via an event is something that could likely change and possibly be made more general and/or reusable, so I’ve kept it separate and hidden for now.

@yhao3 @ch4mpy @filiphr @mlitcher If you have a chance, please review #16589 with my updates and provide feedback. Please feel free to also test this out on the branch, or if you prefer you can just provide feedback and wait until it gets merged and test in a milestone release.

I encountered the same issue when using the Spring OAuth2 client with the Spring Authorization Server.

During the refresh token process, if the scopes include the openid scope, the Spring Authorization Server updates the value of id_token in org.springframework.security.oauth2.server.authorization.OAuth2Authorization. However, on the client side, the SecurityContext does not update the id_token after the refresh token process. This happens because org.springframework.security.oauth2.client.RefreshTokenOAuth2AuthorizedClientProvider does not retrieve and update the new id_token from the additionalParameters in OAuth2AccessTokenResponse.

As a result, when the client side later initiates an RP-Initiated Logout, the value of the id_token_hint parameter in the request still uses the old id_token. This causes the Spring Authorization Server to throw an invalid_token error.

Just wanted to confirm, Spring Authorization Server does refresh the id_token during the refresh token flow and only seems to accept the last one during an RP-initiated logout by default. So, using Spring Cloud Gateway w/ oauth2 client + Spring Authorization Server, you will get an error during RP-initiated logout after the first token refresh due to this issue.

@joaquinjsb I don’t have a public reproducer, which, as I wrote above, is not that easy to make. We’d need:

  • an OAuth2 client with oauth2Login
  • an authorization server accepting only the last emitted ID token for RP-Initiated Logout (this is not complicated as most do, but still requires a Docker compose file with several services, and user database initialization)
  • a UI sending parallel requests
  • an end-to-end script to:
    • login
    • wait until the access token expiration and perform a page reload or whatever triggers the parallel requests
    • perform a logout
  • enough repetitions to have a race condition and a failed logout (the token saved in the OAuth2 client session is not the last emitted by the authorization server)

This is quite some work and is mostly useless, considering that the Spring Security team stated that it is an expected behavior (when using Spring Security, we should serialize requests).

So, for now, the point is more about gathering enough community feedback that parallel requests should be a supported use case, rather than putting reproducers together or even submitting PRs.

Thanks for being patient, and sorry I was unable to look at this closely sooner. I’m doing some thinking about this issue this week. I think the challenges with this issue are as follows:

  1. Information about the id_token is not returned when refreshing an access token. It will be captured in additionalParameters in the OAuth2AccessTokenResponse but is not able to be returned in the resulting OAuth2AuthorizedClient. See #16253.
  2. The RefreshTokenOAuth2AuthorizedClientProvider is likely the best component to “know” that the token is being refreshed (for obvious reasons), and therefore would somehow need to be responsible for updating the SecurityContext. However, it is not related to authentication at all, and therefore should not directly update this.
  3. Also, the RefreshTokenOAuth2AuthorizedClientProvider has no direct knowledge of OIDC, and as such shouldn’t care about an id_token.
  4. Logic for authentication and updating the SecurityContext typically lives in authentication filters and is related directly to authentication requests. This issue is not related to an authentication request, so logic for this update needs to live somewhere else.

With all of that as context, I think that assuming we can somehow solve (1) above, a solution for this issue could be to publish an event from the RefreshTokenOAuth2AuthorizedClientProvider and place logic for updating the SecurityContext in an event listener. Concretely:

  1. Get an ApplicationEventPublisher when it is published as a bean (as we do in other parts of Spring Security) and configure it with RefreshTokenOAuth2AuthorizedClientProvider.
  2. Update RefreshTokenOAuth2AuthorizedClientProvider to publish an ApplicationEvent with all of the relevant information when an ApplicationEventPublisher is available.
  3. Create an ApplicationListener that receives this event, determines that it is refreshing an id_token, and uses a SecurityContextRepository to update the current SecurityContext.

Does anyone have additional thoughts on this?

@sjohnr I think I progressed in my understanding of the root cause for this issue and re-wrote the description accordingly.