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 (
OidcUserorOAuth2User) might contain outdated data - in case of an RP-Initiated Logout, the
OidcClientInitiated(Server)LogoutSuccessHandlermight build a redirection URI to the authorization serverend_session_endpointwith 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.
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
oauth2Clientconfigured withoauth2Loginand RP-Initated Logout - wait until the access token is expired
- have refresh token flow executed. Using the
(Reactive)OAuth2AuthorizedClientManagerto retrieve the access token - like Spring Cloud GatewayTokenRelay=filter does - is enough. - initiate RP-Initiated Logout (send a
POSTrequest to the/logoutendpoint)
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_endpointshould 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:
- https://stackoverflow.com/questions/78901208/spring-authorization-server-refreshes-the-client-tokenoidc-id-token-when-the-a
- https://stackoverflow.com/questions/78685992/issue-in-spring-authorization-server-and-spring-cloud-gateway-refresh-token-flow
- https://stackoverflow.com/questions/77175866/spring-authorization-server-oidc-logout-not-working-after-refreshing-token-in-sp
- https://stackoverflow.com/questions/77665448/oidc-rp-initiated-logout-doesnt-work-once-the-first-access-token-got-refreshed
About this issue
- Original URL
- State: open
- Created 2 years ago
- Reactions: 10
- Comments: 24 (20 by maintainers)
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 anOAuth2AuthorizedClientand the associatedOAuth2AccessTokenResponseby listening for the eventOAuth2AuthorizedClientRefreshedEvent. This listener processes the response and determines if anOidcUserneeds to be refreshed by looking for anid_token. If found, it publishes another event,OidcUserRefreshedEvent.The second listener (
OidcUserRefreshedEventListener) simply listens forOidcUserRefreshedEventand updates theSecurityContext.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 theSecurityContext. I feel that updating of aSecurityContextvia 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
scopesinclude theopenidscope, the Spring Authorization Server updates the value ofid_tokeninorg.springframework.security.oauth2.server.authorization.OAuth2Authorization. However, on the client side, theSecurityContextdoes not update theid_tokenafter the refresh token process. This happens becauseorg.springframework.security.oauth2.client.RefreshTokenOAuth2AuthorizedClientProviderdoes not retrieve and update the newid_tokenfrom theadditionalParametersinOAuth2AccessTokenResponse.As a result, when the client side later initiates an RP-Initiated Logout, the value of the
id_token_hintparameter in the request still uses the oldid_token. This causes the Spring Authorization Server to throw aninvalid_tokenerror.Just wanted to confirm, Spring Authorization Server does refresh the
id_tokenduring 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:
oauth2LoginThis 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:
id_tokenis not returned when refreshing an access token. It will be captured inadditionalParametersin theOAuth2AccessTokenResponsebut is not able to be returned in the resultingOAuth2AuthorizedClient. See #16253.RefreshTokenOAuth2AuthorizedClientProvideris 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 theSecurityContext. However, it is not related to authentication at all, and therefore should not directly update this.RefreshTokenOAuth2AuthorizedClientProviderhas no direct knowledge of OIDC, and as such shouldn’t care about anid_token.SecurityContexttypically 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
RefreshTokenOAuth2AuthorizedClientProviderand place logic for updating theSecurityContextin an event listener. Concretely:ApplicationEventPublisherwhen it is published as a bean (as we do in other parts of Spring Security) and configure it withRefreshTokenOAuth2AuthorizedClientProvider.RefreshTokenOAuth2AuthorizedClientProviderto publish anApplicationEventwith all of the relevant information when anApplicationEventPublisheris available.ApplicationListenerthat receives this event, determines that it is refreshing anid_token, and uses aSecurityContextRepositoryto update the currentSecurityContext.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.