|  | 
|  | 1 | +/* | 
|  | 2 | + * Copyright 2002-2025 the original author or authors. | 
|  | 3 | + * | 
|  | 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | 
|  | 5 | + * you may not use this file except in compliance with the License. | 
|  | 6 | + * You may obtain a copy of the License at | 
|  | 7 | + * | 
|  | 8 | + *      https://www.apache.org/licenses/LICENSE-2.0 | 
|  | 9 | + * | 
|  | 10 | + * Unless required by applicable law or agreed to in writing, software | 
|  | 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | 
|  | 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | 
|  | 13 | + * See the License for the specific language governing permissions and | 
|  | 14 | + * limitations under the License. | 
|  | 15 | + */ | 
|  | 16 | + | 
|  | 17 | +package org.springframework.security.oauth2.client.oidc.authentication; | 
|  | 18 | + | 
|  | 19 | +import java.util.Map; | 
|  | 20 | + | 
|  | 21 | +import org.springframework.context.ApplicationListener; | 
|  | 22 | +import org.springframework.security.core.Authentication; | 
|  | 23 | +import org.springframework.security.core.context.SecurityContext; | 
|  | 24 | +import org.springframework.security.core.context.SecurityContextHolder; | 
|  | 25 | +import org.springframework.security.core.context.SecurityContextHolderStrategy; | 
|  | 26 | +import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; | 
|  | 27 | +import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; | 
|  | 28 | +import org.springframework.security.oauth2.client.event.OAuth2TokenRefreshedEvent; | 
|  | 29 | +import org.springframework.security.oauth2.client.registration.ClientRegistration; | 
|  | 30 | +import org.springframework.security.oauth2.core.OAuth2AuthenticationException; | 
|  | 31 | +import org.springframework.security.oauth2.core.OAuth2Error; | 
|  | 32 | +import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; | 
|  | 33 | +import org.springframework.security.oauth2.core.oidc.OidcIdToken; | 
|  | 34 | +import org.springframework.security.oauth2.core.oidc.OidcScopes; | 
|  | 35 | +import org.springframework.security.oauth2.core.oidc.StandardClaimNames; | 
|  | 36 | +import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames; | 
|  | 37 | +import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; | 
|  | 38 | +import org.springframework.security.oauth2.core.oidc.user.OidcUser; | 
|  | 39 | +import org.springframework.security.oauth2.jwt.Jwt; | 
|  | 40 | +import org.springframework.security.oauth2.jwt.JwtDecoder; | 
|  | 41 | +import org.springframework.security.oauth2.jwt.JwtDecoderFactory; | 
|  | 42 | +import org.springframework.security.oauth2.jwt.JwtException; | 
|  | 43 | +import org.springframework.util.Assert; | 
|  | 44 | + | 
|  | 45 | +/** | 
|  | 46 | + * An {@link ApplicationListener} that listens for {@link OAuth2TokenRefreshedEvent}s | 
|  | 47 | + */ | 
|  | 48 | +public class RefreshOidcIdTokenHandler implements ApplicationListener<OAuth2TokenRefreshedEvent> { | 
|  | 49 | + | 
|  | 50 | +	private static final String MISSING_ID_TOKEN_ERROR_CODE = "missing_id_token"; | 
|  | 51 | + | 
|  | 52 | +	private static final String INVALID_ID_TOKEN_ERROR_CODE = "invalid_id_token"; | 
|  | 53 | + | 
|  | 54 | +	private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder | 
|  | 55 | +		.getContextHolderStrategy(); | 
|  | 56 | + | 
|  | 57 | +	private JwtDecoderFactory<ClientRegistration> jwtDecoderFactory = new OidcIdTokenDecoderFactory(); | 
|  | 58 | + | 
|  | 59 | +	@Override | 
|  | 60 | +	public void onApplicationEvent(OAuth2TokenRefreshedEvent event) { | 
|  | 61 | +		OAuth2AuthorizedClient authorizedClient = event.getAuthorizedClient(); | 
|  | 62 | + | 
|  | 63 | +		if (!authorizedClient.getClientRegistration().getScopes().contains(OidcScopes.OPENID)) { | 
|  | 64 | +			return; | 
|  | 65 | +		} | 
|  | 66 | + | 
|  | 67 | +		Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication(); | 
|  | 68 | +		if (!(authentication instanceof OAuth2AuthenticationToken oauth2Authentication)) { | 
|  | 69 | +			return; | 
|  | 70 | +		} | 
|  | 71 | +		if (!(authentication.getPrincipal() instanceof DefaultOidcUser defaultOidcUser)) { | 
|  | 72 | +			return; | 
|  | 73 | +		} | 
|  | 74 | + | 
|  | 75 | +		OAuth2AccessTokenResponse accessTokenResponse = event.getAccessTokenResponse(); | 
|  | 76 | + | 
|  | 77 | +		String idToken = (String) accessTokenResponse.getAdditionalParameters().get(OidcParameterNames.ID_TOKEN); | 
|  | 78 | +		if (idToken == null || idToken.isBlank()) { | 
|  | 79 | +			OAuth2Error missingIdTokenError = new OAuth2Error(MISSING_ID_TOKEN_ERROR_CODE, | 
|  | 80 | +					"ID token is missing in the token response", null); | 
|  | 81 | +			throw new OAuth2AuthenticationException(missingIdTokenError, missingIdTokenError.toString()); | 
|  | 82 | +		} | 
|  | 83 | + | 
|  | 84 | +		ClientRegistration clientRegistration = authorizedClient.getClientRegistration(); | 
|  | 85 | +		OidcIdToken refreshedOidcToken = createOidcToken(clientRegistration, accessTokenResponse); | 
|  | 86 | +		updateSecurityContext(oauth2Authentication, defaultOidcUser, refreshedOidcToken); | 
|  | 87 | +	} | 
|  | 88 | + | 
|  | 89 | +	/** | 
|  | 90 | +	 * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use | 
|  | 91 | +	 * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. | 
|  | 92 | +	 */ | 
|  | 93 | +	public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { | 
|  | 94 | +		this.securityContextHolderStrategy = securityContextHolderStrategy; | 
|  | 95 | +	} | 
|  | 96 | + | 
|  | 97 | +	/** | 
|  | 98 | +	 * Sets the {@link JwtDecoderFactory} used for {@link OidcIdToken} signature | 
|  | 99 | +	 * verification. The factory returns a {@link JwtDecoder} associated to the provided | 
|  | 100 | +	 * {@link ClientRegistration}. | 
|  | 101 | +	 * @param jwtDecoderFactory the {@link JwtDecoderFactory} used for {@link OidcIdToken} | 
|  | 102 | +	 * signature verification | 
|  | 103 | +	 */ | 
|  | 104 | +	public final void setJwtDecoderFactory(JwtDecoderFactory<ClientRegistration> jwtDecoderFactory) { | 
|  | 105 | +		Assert.notNull(jwtDecoderFactory, "jwtDecoderFactory cannot be null"); | 
|  | 106 | +		this.jwtDecoderFactory = jwtDecoderFactory; | 
|  | 107 | +	} | 
|  | 108 | + | 
|  | 109 | +	private void updateSecurityContext(OAuth2AuthenticationToken oauth2Authentication, DefaultOidcUser defaultOidcUser, | 
|  | 110 | +			OidcIdToken refreshedOidcToken) { | 
|  | 111 | +		OidcUser oidcUser = new DefaultOidcUser(defaultOidcUser.getAuthorities(), refreshedOidcToken, | 
|  | 112 | +				defaultOidcUser.getUserInfo(), StandardClaimNames.SUB); | 
|  | 113 | + | 
|  | 114 | +		SecurityContext context = this.securityContextHolderStrategy.createEmptyContext(); | 
|  | 115 | +		context.setAuthentication(new OAuth2AuthenticationToken(oidcUser, oidcUser.getAuthorities(), | 
|  | 116 | +				oauth2Authentication.getAuthorizedClientRegistrationId())); | 
|  | 117 | + | 
|  | 118 | +		this.securityContextHolderStrategy.setContext(context); | 
|  | 119 | +	} | 
|  | 120 | + | 
|  | 121 | +	private OidcIdToken createOidcToken(ClientRegistration clientRegistration, | 
|  | 122 | +			OAuth2AccessTokenResponse accessTokenResponse) { | 
|  | 123 | +		JwtDecoder jwtDecoder = this.jwtDecoderFactory.createDecoder(clientRegistration); | 
|  | 124 | +		Jwt jwt = getJwt(accessTokenResponse, jwtDecoder); | 
|  | 125 | +		return new OidcIdToken(jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt(), jwt.getClaims()); | 
|  | 126 | +	} | 
|  | 127 | + | 
|  | 128 | +	private Jwt getJwt(OAuth2AccessTokenResponse accessTokenResponse, JwtDecoder jwtDecoder) { | 
|  | 129 | +		try { | 
|  | 130 | +			Map<String, Object> parameters = accessTokenResponse.getAdditionalParameters(); | 
|  | 131 | +			return jwtDecoder.decode((String) parameters.get(OidcParameterNames.ID_TOKEN)); | 
|  | 132 | +		} | 
|  | 133 | +		catch (JwtException ex) { | 
|  | 134 | +			OAuth2Error invalidIdTokenError = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, ex.getMessage(), null); | 
|  | 135 | +			throw new OAuth2AuthenticationException(invalidIdTokenError, invalidIdTokenError.toString(), ex); | 
|  | 136 | +		} | 
|  | 137 | +	} | 
|  | 138 | + | 
|  | 139 | +} | 
0 commit comments