Search in sources :

Example 16 with OAuth2RefreshToken

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;
}
Also used : OAuth2RefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken) DefaultOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken) DefaultOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) Date(java.util.Date)

Example 17 with OAuth2RefreshToken

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;
}
Also used : OAuth2RefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) Authentication(org.springframework.security.core.Authentication) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException)

Example 18 with OAuth2RefreshToken

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));
}
Also used : DefaultOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken) DefaultExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken) OAuth2RefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken) DefaultOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) DefaultExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken) Date(java.util.Date) Test(org.junit.Test)

Example 19 with OAuth2RefreshToken

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");
}
Also used : ServerWebExchange(org.springframework.web.server.ServerWebExchange) MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Instant(java.time.Instant) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Test(org.junit.jupiter.api.Test)

Example 20 with OAuth2RefreshToken

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");
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Instant(java.time.Instant) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2RefreshToken (org.springframework.security.oauth2.core.OAuth2RefreshToken)32 Test (org.junit.jupiter.api.Test)29 OAuth2RefreshToken (org.springframework.security.oauth2.common.OAuth2RefreshToken)26 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)22 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)22 ClientRequest (org.springframework.web.reactive.function.client.ClientRequest)18 DefaultOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken)17 DefaultExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken)16 ExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken)14 Test (org.junit.Test)13 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)12 Instant (java.time.Instant)11 Date (java.util.Date)11 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)11 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)10 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)9 HashMap (java.util.HashMap)8 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)8 HttpHeaders (org.springframework.http.HttpHeaders)5 LinkedHashMap (java.util.LinkedHashMap)4