use of org.springframework.security.oauth2.core.OAuth2RefreshToken in project ORCID-Source by ORCID.
the class OrcidRandomValueTokenServicesImpl method generateAccessToken.
private DefaultOAuth2AccessToken generateAccessToken(OAuth2Authentication authentication) {
DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(UUID.randomUUID().toString());
int validitySeconds = getAccessTokenValiditySeconds(authentication.getOAuth2Request());
if (validitySeconds > 0) {
accessToken.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
}
accessToken.setScope(authentication.getOAuth2Request().getScope());
if (customTokenEnhancer != null) {
accessToken = new DefaultOAuth2AccessToken(customTokenEnhancer.enhance(accessToken, authentication));
}
if (this.isSupportRefreshToken(authentication.getOAuth2Request())) {
OAuth2RefreshToken refreshToken = new DefaultOAuth2RefreshToken(UUID.randomUUID().toString());
accessToken.setRefreshToken(refreshToken);
}
return accessToken;
}
use of org.springframework.security.oauth2.core.OAuth2RefreshToken in project spring-security-oauth by spring-projects.
the class AccessTokenProviderChain method obtainAccessToken.
public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails resource, AccessTokenRequest request) throws UserRedirectRequiredException, AccessDeniedException {
OAuth2AccessToken accessToken = null;
OAuth2AccessToken existingToken = null;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth instanceof AnonymousAuthenticationToken) {
if (!resource.isClientOnly()) {
throw new InsufficientAuthenticationException("Authentication is required to obtain an access token (anonymous not allowed)");
}
}
if (resource.isClientOnly() || (auth != null && auth.isAuthenticated())) {
existingToken = request.getExistingToken();
if (existingToken == null && clientTokenServices != null) {
existingToken = clientTokenServices.getAccessToken(resource, auth);
}
if (existingToken != null) {
if (existingToken.isExpired()) {
if (clientTokenServices != null) {
clientTokenServices.removeAccessToken(resource, auth);
}
OAuth2RefreshToken refreshToken = existingToken.getRefreshToken();
if (refreshToken != null && !resource.isClientOnly()) {
accessToken = refreshAccessToken(resource, refreshToken, request);
}
} else {
accessToken = existingToken;
}
}
}
if (accessToken == null) {
// looks like we need to try to obtain a new token.
accessToken = obtainNewAccessTokenInternal(resource, request);
if (accessToken == null) {
throw new IllegalStateException("An OAuth 2 access token must be obtained or an exception thrown.");
}
}
if (clientTokenServices != null && (resource.isClientOnly() || auth != null && auth.isAuthenticated())) {
clientTokenServices.saveAccessToken(resource, auth, accessToken);
}
return accessToken;
}
use of org.springframework.security.oauth2.core.OAuth2RefreshToken in project spring-security-oauth by spring-projects.
the class RedisTokenStoreTests method testExpiringRefreshToken.
@Test
public void testExpiringRefreshToken() throws InterruptedException {
String refreshToken = UUID.randomUUID().toString();
DefaultOAuth2RefreshToken expectedExpiringRefreshToken = new DefaultExpiringOAuth2RefreshToken(refreshToken, new Date(System.currentTimeMillis() + 1500));
OAuth2Authentication expectedAuthentication = new OAuth2Authentication(RequestTokenFactory.createOAuth2Request("id", false), new TestAuthentication("test2", false));
getTokenStore().storeRefreshToken(expectedExpiringRefreshToken, expectedAuthentication);
OAuth2RefreshToken actualExpiringRefreshToken = getTokenStore().readRefreshToken(refreshToken);
assertEquals(expectedExpiringRefreshToken, actualExpiringRefreshToken);
assertEquals(expectedAuthentication, getTokenStore().readAuthenticationForRefreshToken(expectedExpiringRefreshToken));
// let the token expire
Thread.sleep(1500);
// now it should be gone
assertNull(getTokenStore().readRefreshToken(refreshToken));
assertNull(getTokenStore().readAuthenticationForRefreshToken(expectedExpiringRefreshToken));
}
use of org.springframework.security.oauth2.core.OAuth2RefreshToken in project spring-security by spring-projects.
the class ServerOAuth2AuthorizedClientExchangeFilterFunctionITests method requestWhenAuthorizedButExpiredThenRefreshAndSendRequest.
@Test
public void requestWhenAuthorizedButExpiredThenRefreshAndSendRequest() {
// @formatter:off
String accessTokenResponse = "{\n" + " \"access_token\": \"refreshed-access-token\",\n" + " \"token_type\": \"bearer\",\n" + " \"expires_in\": \"3600\"\n" + "}\n";
String clientResponse = "{\n" + " \"attribute1\": \"value1\",\n" + " \"attribute2\": \"value2\"\n" + "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenResponse));
this.server.enqueue(jsonResponse(clientResponse));
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().tokenUri(this.serverUrl).build();
given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration.getRegistrationId()))).willReturn(Mono.just(clientRegistration));
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant expiresAt = issuedAt.plus(Duration.ofHours(1));
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "expired-access-token", issuedAt, expiresAt, new HashSet<>(Arrays.asList("read", "write")));
OAuth2RefreshToken refreshToken = TestOAuth2RefreshTokens.refreshToken();
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, this.authentication.getName(), accessToken, refreshToken);
doReturn(Mono.just(authorizedClient)).when(this.authorizedClientRepository).loadAuthorizedClient(eq(clientRegistration.getRegistrationId()), eq(this.authentication), eq(this.exchange));
this.webClient.get().uri(this.serverUrl).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(clientRegistration.getRegistrationId())).retrieve().bodyToMono(String.class).subscriberContext(Context.of(ServerWebExchange.class, this.exchange)).subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)).block();
assertThat(this.server.getRequestCount()).isEqualTo(2);
ArgumentCaptor<OAuth2AuthorizedClient> authorizedClientCaptor = ArgumentCaptor.forClass(OAuth2AuthorizedClient.class);
verify(this.authorizedClientRepository).saveAuthorizedClient(authorizedClientCaptor.capture(), eq(this.authentication), eq(this.exchange));
OAuth2AuthorizedClient refreshedAuthorizedClient = authorizedClientCaptor.getValue();
assertThat(refreshedAuthorizedClient.getClientRegistration()).isSameAs(clientRegistration);
assertThat(refreshedAuthorizedClient.getAccessToken().getTokenValue()).isEqualTo("refreshed-access-token");
}
use of org.springframework.security.oauth2.core.OAuth2RefreshToken in project spring-security by spring-projects.
the class ServletOAuth2AuthorizedClientExchangeFilterFunctionITests method requestWhenAuthorizedButExpiredThenRefreshAndSendRequest.
@Test
public void requestWhenAuthorizedButExpiredThenRefreshAndSendRequest() {
// @formatter:off
String accessTokenResponse = "{\n" + " \"access_token\": \"refreshed-access-token\",\n" + " \"token_type\": \"bearer\",\n" + " \"expires_in\": \"3600\"\n" + "}\n";
String clientResponse = "{\n" + " \"attribute1\": \"value1\",\n" + " \"attribute2\": \"value2\"\n" + "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenResponse));
this.server.enqueue(jsonResponse(clientResponse));
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().tokenUri(this.serverUrl).build();
given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration.getRegistrationId()))).willReturn(clientRegistration);
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant expiresAt = issuedAt.plus(Duration.ofHours(1));
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "expired-access-token", issuedAt, expiresAt, new HashSet<>(Arrays.asList("read", "write")));
OAuth2RefreshToken refreshToken = TestOAuth2RefreshTokens.refreshToken();
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, this.authentication.getName(), accessToken, refreshToken);
doReturn(authorizedClient).when(this.authorizedClientRepository).loadAuthorizedClient(eq(clientRegistration.getRegistrationId()), eq(this.authentication), eq(this.request));
this.webClient.get().uri(this.serverUrl).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(clientRegistration.getRegistrationId())).retrieve().bodyToMono(String.class).block();
assertThat(this.server.getRequestCount()).isEqualTo(2);
ArgumentCaptor<OAuth2AuthorizedClient> authorizedClientCaptor = ArgumentCaptor.forClass(OAuth2AuthorizedClient.class);
verify(this.authorizedClientRepository).saveAuthorizedClient(authorizedClientCaptor.capture(), eq(this.authentication), eq(this.request), eq(this.response));
OAuth2AuthorizedClient refreshedAuthorizedClient = authorizedClientCaptor.getValue();
assertThat(refreshedAuthorizedClient.getClientRegistration()).isSameAs(clientRegistration);
assertThat(refreshedAuthorizedClient.getAccessToken().getTokenValue()).isEqualTo("refreshed-access-token");
}
Aggregations