Search in sources :

Example 56 with OAuth2RefreshToken

use of org.springframework.security.oauth2.core.OAuth2RefreshToken in project LeoGitRepo by lihao95.

the class ExtRedisTokenStore method storeRefreshToken.

@Override
public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
    byte[] refreshKey = serializeKey(REFRESH + refreshToken.getValue());
    byte[] refreshAuthKey = serializeKey(REFRESH_AUTH + refreshToken.getValue());
    byte[] serializedRefreshToken = serialize(refreshToken);
    RedisConnection conn = getConnection();
    try {
        conn.openPipeline();
        conn.stringCommands().set(refreshKey, serializedRefreshToken);
        conn.stringCommands().set(refreshAuthKey, serialize(authentication));
        if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
            ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken;
            Date expiration = expiringRefreshToken.getExpiration();
            if (expiration != null) {
                int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L).intValue();
                conn.expire(refreshKey, seconds);
                conn.expire(refreshAuthKey, seconds);
            }
        }
        conn.closePipeline();
    } finally {
        conn.close();
    }
}
Also used : RedisConnection(org.springframework.data.redis.connection.RedisConnection) ExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken)

Example 57 with OAuth2RefreshToken

use of org.springframework.security.oauth2.core.OAuth2RefreshToken in project spring-security-oauth by spring-projects.

the class DefaultTokenServices method createAccessToken.

private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) {
    String tokenValue = new String(Base64.encodeBase64URLSafe(DEFAULT_TOKEN_GENERATOR.generateKey()), US_ASCII);
    DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(tokenValue);
    int validitySeconds = getAccessTokenValiditySeconds(authentication.getOAuth2Request());
    if (validitySeconds > 0) {
        token.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
    }
    token.setRefreshToken(refreshToken);
    token.setScope(authentication.getOAuth2Request().getScope());
    return accessTokenEnhancer != null ? accessTokenEnhancer.enhance(token, authentication) : token;
}
Also used : DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) Date(java.util.Date)

Example 58 with OAuth2RefreshToken

use of org.springframework.security.oauth2.core.OAuth2RefreshToken in project spring-security-oauth by spring-projects.

the class DefaultTokenServices method refreshAccessToken.

@Transactional(noRollbackFor = { InvalidTokenException.class, InvalidGrantException.class })
public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest tokenRequest) throws AuthenticationException {
    if (!supportRefreshToken) {
        throw new InvalidGrantException("Invalid refresh token");
    }
    OAuth2RefreshToken refreshToken = tokenStore.readRefreshToken(refreshTokenValue);
    if (refreshToken == null) {
        throw new InvalidGrantException("Invalid refresh token");
    }
    OAuth2Authentication authentication = tokenStore.readAuthenticationForRefreshToken(refreshToken);
    if (this.authenticationManager != null && !authentication.isClientOnly()) {
        // The client has already been authenticated, but the user authentication might be old now, so give it a
        // chance to re-authenticate.
        Authentication userAuthentication = authentication.getUserAuthentication();
        PreAuthenticatedAuthenticationToken preAuthenticatedToken = new PreAuthenticatedAuthenticationToken(userAuthentication, "", authentication.getAuthorities());
        if (userAuthentication.getDetails() != null) {
            preAuthenticatedToken.setDetails(userAuthentication.getDetails());
        }
        Authentication user = authenticationManager.authenticate(preAuthenticatedToken);
        Object details = authentication.getDetails();
        authentication = new OAuth2Authentication(authentication.getOAuth2Request(), user);
        authentication.setDetails(details);
    }
    String clientId = authentication.getOAuth2Request().getClientId();
    if (clientId == null || !clientId.equals(tokenRequest.getClientId())) {
        throw new InvalidGrantException("Wrong client for this refresh token");
    }
    // clear out any access tokens already associated with the refresh
    // token.
    tokenStore.removeAccessTokenUsingRefreshToken(refreshToken);
    if (isExpired(refreshToken)) {
        tokenStore.removeRefreshToken(refreshToken);
        throw new InvalidTokenException("Invalid refresh token (expired)");
    }
    authentication = createRefreshedAuthentication(authentication, tokenRequest);
    if (!reuseRefreshToken) {
        tokenStore.removeRefreshToken(refreshToken);
        refreshToken = createRefreshToken(authentication);
    }
    OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken);
    tokenStore.storeAccessToken(accessToken, authentication);
    if (!reuseRefreshToken) {
        tokenStore.storeRefreshToken(accessToken.getRefreshToken(), authentication);
    }
    return accessToken;
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) ExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken) OAuth2RefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken) DefaultOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken) DefaultExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 59 with OAuth2RefreshToken

use of org.springframework.security.oauth2.core.OAuth2RefreshToken in project spring-security-oauth by spring-projects.

the class RedisTokenStoreMockTests method storeRefreshTokenRemoveRefreshTokenVerifyKeysRemoved.

// gh-572
@Test
public void storeRefreshTokenRemoveRefreshTokenVerifyKeysRemoved() {
    OAuth2RefreshToken oauth2RefreshToken = new DefaultOAuth2RefreshToken("refresh-token-" + UUID.randomUUID());
    OAuth2Authentication oauth2Authentication = new OAuth2Authentication(request, authentication);
    tokenStore.storeRefreshToken(oauth2RefreshToken, oauth2Authentication);
    ArgumentCaptor<byte[]> keyArgs = ArgumentCaptor.forClass(byte[].class);
    verify(connection, times(2)).set(keyArgs.capture(), any(byte[].class));
    List<Object> result = new ArrayList<Object>();
    result.add(Long.valueOf(1));
    result.add(Long.valueOf(1));
    result.add(new byte[] { 42 });
    result.add(Long.valueOf(1));
    when(connection.closePipeline()).thenReturn(result);
    tokenStore.removeRefreshToken(oauth2RefreshToken);
    for (byte[] key : keyArgs.getAllValues()) {
        verify(connection).del(key);
    }
}
Also used : DefaultOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken) OAuth2RefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken) DefaultOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Test(org.junit.Test)

Example 60 with OAuth2RefreshToken

use of org.springframework.security.oauth2.core.OAuth2RefreshToken in project spring-security-oauth by spring-projects.

the class RedisTokenStorePrefixTests 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)

Aggregations

OAuth2RefreshToken (org.springframework.security.oauth2.common.OAuth2RefreshToken)74 OAuth2RefreshToken (org.springframework.security.oauth2.core.OAuth2RefreshToken)57 Test (org.junit.jupiter.api.Test)41 Test (org.junit.Test)39 DefaultOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken)38 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)33 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)31 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)25 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)25 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)24 ExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken)24 Authentication (org.springframework.security.core.Authentication)20 Instant (java.time.Instant)19 ClientRequest (org.springframework.web.reactive.function.client.ClientRequest)18 RegisteredClient (org.springframework.security.oauth2.server.authorization.client.RegisteredClient)17 DefaultExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken)16 HashMap (java.util.HashMap)15 OAuth2Authorization (org.springframework.security.oauth2.server.authorization.OAuth2Authorization)14 RedisConnection (org.springframework.data.redis.connection.RedisConnection)13 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)13