Skip to content

Preserve existing refresh token if new refresh token not returned #6504

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -45,6 +45,7 @@
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;

import static org.springframework.security.oauth2.core.web.reactive.function.OAuth2BodyExtractors.oauth2AccessTokenResponse;
Expand Down Expand Up @@ -289,7 +290,11 @@ private Mono<OAuth2AuthorizedClient> authorizeWithRefreshToken(ExchangeFunction
.build();
return next.exchange(refreshRequest)
.flatMap(refreshResponse -> refreshResponse.body(oauth2AccessTokenResponse()))
.map(accessTokenResponse -> new OAuth2AuthorizedClient(authorizedClient.getClientRegistration(), authorizedClient.getPrincipalName(), accessTokenResponse.getAccessToken(), accessTokenResponse.getRefreshToken()))
.map(accessTokenResponse -> {
OAuth2RefreshToken refreshToken = Optional.ofNullable(accessTokenResponse.getRefreshToken())
.orElse(authorizedClient.getRefreshToken());
return new OAuth2AuthorizedClient(authorizedClient.getClientRegistration(), authorizedClient.getPrincipalName(), accessTokenResponse.getAccessToken(), refreshToken);
})
.flatMap(result -> this.authorizedClientRepository.saveAuthorizedClient(result, authentication, exchange)
.thenReturn(result));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -391,7 +391,11 @@ private Mono<OAuth2AuthorizedClient> authorizeWithRefreshToken(ClientRequest req
.build();
return next.exchange(refreshRequest)
.flatMap(response -> response.body(oauth2AccessTokenResponse()))
.map(accessTokenResponse -> new OAuth2AuthorizedClient(authorizedClient.getClientRegistration(), authorizedClient.getPrincipalName(), accessTokenResponse.getAccessToken(), accessTokenResponse.getRefreshToken()))
.map(accessTokenResponse -> {
OAuth2RefreshToken refreshToken = Optional.ofNullable(accessTokenResponse.getRefreshToken())
.orElse(authorizedClient.getRefreshToken());
return new OAuth2AuthorizedClient(authorizedClient.getClientRegistration(), authorizedClient.getPrincipalName(), accessTokenResponse.getAccessToken(), refreshToken);
})
.map(result -> {
Authentication principal = (Authentication) request.attribute(
AUTHENTICATION_ATTR_NAME).orElse(new PrincipalNameAuthentication(authorizedClient.getPrincipalName()));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -19,6 +19,8 @@
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.codec.ByteBufferEncoder;
Expand Down Expand Up @@ -94,6 +96,9 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests {
@Mock
private ServerWebExchange serverWebExchange;

@Captor
private ArgumentCaptor<OAuth2AuthorizedClient> authorizedClientCaptor;

private ServerOAuth2AuthorizedClientExchangeFilterFunction function;

private MockExchangeFunction exchange = new MockExchangeFunction();
Expand Down Expand Up @@ -260,7 +265,62 @@ public void filterWhenRefreshRequiredThenRefresh() {
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication))
.block();

verify(this.authorizedClientRepository).saveAuthorizedClient(any(), eq(authentication), any());
verify(this.authorizedClientRepository).saveAuthorizedClient(this.authorizedClientCaptor.capture(), eq(authentication), any());

OAuth2AuthorizedClient newAuthorizedClient = authorizedClientCaptor.getValue();
assertThat(newAuthorizedClient.getAccessToken()).isEqualTo(response.getAccessToken());
assertThat(newAuthorizedClient.getRefreshToken()).isEqualTo(response.getRefreshToken());

List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(2);

ClientRequest request0 = requests.get(0);
assertThat(request0.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
assertThat(request0.url().toASCIIString()).isEqualTo("https://example.com/login/oauth/access_token");
assertThat(request0.method()).isEqualTo(HttpMethod.POST);
assertThat(getBody(request0)).isEqualTo("grant_type=refresh_token&refresh_token=refresh-token");

ClientRequest request1 = requests.get(1);
assertThat(request1.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-1");
assertThat(request1.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request1.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request1)).isEmpty();
}

@Test
public void filterWhenRefreshRequiredThenRefreshAndResponseDoesNotContainRefreshToken() {
when(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).thenReturn(Mono.empty());
OAuth2AccessTokenResponse response = OAuth2AccessTokenResponse.withToken("token-1")
.tokenType(OAuth2AccessToken.TokenType.BEARER)
.expiresIn(3600)
// .refreshToken(xxx) // No refreshToken in response
.build();
when(this.exchange.getResponse().body(any())).thenReturn(Mono.just(response));
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant accessTokenExpiresAt = issuedAt.plus(Duration.ofHours(1));

this.accessToken = new OAuth2AccessToken(this.accessToken.getTokenType(),
this.accessToken.getTokenValue(),
issuedAt,
accessTokenExpiresAt);

OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", issuedAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration,
"principalName", this.accessToken, refreshToken);
ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com"))
.attributes(oauth2AuthorizedClient(authorizedClient))
.build();

TestingAuthenticationToken authentication = new TestingAuthenticationToken("test", "this");
this.function.filter(request, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication))
.block();

verify(this.authorizedClientRepository).saveAuthorizedClient(this.authorizedClientCaptor.capture(), eq(authentication), any());

OAuth2AuthorizedClient newAuthorizedClient = authorizedClientCaptor.getValue();
assertThat(newAuthorizedClient.getAccessToken()).isEqualTo(response.getAccessToken());
assertThat(newAuthorizedClient.getRefreshToken()).isEqualTo(authorizedClient.getRefreshToken());

List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(2);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -101,6 +101,8 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests {
private WebClient.RequestHeadersSpec<?> spec;
@Captor
private ArgumentCaptor<Consumer<Map<String, Object>>> attrs;
@Captor
private ArgumentCaptor<OAuth2AuthorizedClient> authorizedClientCaptor;

/**
* Used for get the attributes from defaultRequest.
Expand Down Expand Up @@ -406,7 +408,61 @@ public void filterWhenRefreshRequiredThenRefresh() {

this.function.filter(request, this.exchange).block();

verify(this.authorizedClientRepository).saveAuthorizedClient(any(), eq(this.authentication), any(), any());
verify(this.authorizedClientRepository).saveAuthorizedClient(this.authorizedClientCaptor.capture(), eq(this.authentication), any(), any());

OAuth2AuthorizedClient newAuthorizedClient = authorizedClientCaptor.getValue();
assertThat(newAuthorizedClient.getAccessToken()).isEqualTo(response.getAccessToken());
assertThat(newAuthorizedClient.getRefreshToken()).isEqualTo(response.getRefreshToken());

List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(2);

ClientRequest request0 = requests.get(0);
assertThat(request0.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Basic Y2xpZW50LWlkOmNsaWVudC1zZWNyZXQ=");
assertThat(request0.url().toASCIIString()).isEqualTo("https://example.com/login/oauth/access_token");
assertThat(request0.method()).isEqualTo(HttpMethod.POST);
assertThat(getBody(request0)).isEqualTo("grant_type=refresh_token&refresh_token=refresh-token");

ClientRequest request1 = requests.get(1);
assertThat(request1.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-1");
assertThat(request1.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request1.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request1)).isEmpty();
}

@Test
public void filterWhenRefreshRequiredThenRefreshAndResponseDoesNotContainRefreshToken() {
OAuth2AccessTokenResponse response = OAuth2AccessTokenResponse.withToken("token-1")
.tokenType(OAuth2AccessToken.TokenType.BEARER)
.expiresIn(3600)
// .refreshToken(xxx) // No refreshToken in response
.build();
when(this.exchange.getResponse().body(any())).thenReturn(Mono.just(response));
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant accessTokenExpiresAt = issuedAt.plus(Duration.ofHours(1));

this.accessToken = new OAuth2AccessToken(this.accessToken.getTokenType(),
this.accessToken.getTokenValue(),
issuedAt,
accessTokenExpiresAt);
this.function = new ServletOAuth2AuthorizedClientExchangeFilterFunction(this.clientRegistrationRepository,
this.authorizedClientRepository);

OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", issuedAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration,
"principalName", this.accessToken, refreshToken);
ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com"))
.attributes(oauth2AuthorizedClient(authorizedClient))
.attributes(authentication(this.authentication))
.build();

this.function.filter(request, this.exchange).block();

verify(this.authorizedClientRepository).saveAuthorizedClient(this.authorizedClientCaptor.capture(), eq(this.authentication), any(), any());

OAuth2AuthorizedClient newAuthorizedClient = authorizedClientCaptor.getValue();
assertThat(newAuthorizedClient.getAccessToken()).isEqualTo(response.getAccessToken());
assertThat(newAuthorizedClient.getRefreshToken()).isEqualTo(refreshToken);

List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(2);
Expand Down