Search in sources :

Example 96 with OAuth2RefreshToken

use of org.springframework.security.oauth2.core.OAuth2RefreshToken in project pig by pig-mesh.

the class PigTokenEndpoint method removeToken.

/**
 * 令牌管理调用
 * @param token token
 */
@Inner
@DeleteMapping("/{token}")
public R<Boolean> removeToken(@PathVariable("token") String token) {
    OAuth2AccessToken accessToken = tokenStore.readAccessToken(token);
    if (accessToken == null || StrUtil.isBlank(accessToken.getValue())) {
        return R.ok();
    }
    OAuth2Authentication auth2Authentication = tokenStore.readAuthentication(accessToken);
    // 清空用户信息
    cacheManager.getCache(CacheConstants.USER_DETAILS).evict(auth2Authentication.getName());
    // 清空access token
    tokenStore.removeAccessToken(accessToken);
    // 清空 refresh token
    OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
    tokenStore.removeRefreshToken(refreshToken);
    // 处理自定义退出事件,保存相关日志
    SpringContextHolder.publishEvent(new LogoutSuccessEvent(auth2Authentication));
    return R.ok();
}
Also used : OAuth2RefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken) LogoutSuccessEvent(org.springframework.security.authentication.event.LogoutSuccessEvent) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Inner(com.pig4cloud.pig.common.security.annotation.Inner)

Example 97 with OAuth2RefreshToken

use of org.springframework.security.oauth2.core.OAuth2RefreshToken in project pig by pig-mesh.

the class PigCustomTokenServices 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: " + refreshTokenValue);
    }
    OAuth2RefreshToken refreshToken = tokenStore.readRefreshToken(refreshTokenValue);
    if (refreshToken == null) {
        throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
    }
    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 user = new PreAuthenticatedAuthenticationToken(authentication.getUserAuthentication(), "", authentication.getAuthorities());
        user = authenticationManager.authenticate(user);
        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: " + refreshTokenValue);
    }
    // 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): " + refreshToken);
    }
    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) Authentication(org.springframework.security.core.Authentication) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 98 with OAuth2RefreshToken

use of org.springframework.security.oauth2.core.OAuth2RefreshToken in project anan-cloud by fosin.

the class AnanTokenServices method createAccessToken.

@Override
public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {
    OAuth2AccessToken existingAccessToken = tokenStore.getAccessToken(authentication);
    OAuth2RefreshToken refreshToken = null;
    if (existingAccessToken != null) {
        // 通过IP地址判断是否异地登录,如果是异地登录则先清除之前认证Token信息
        Authentication userAuthentication = authentication.getUserAuthentication();
        boolean landFall = false;
        if (userAuthentication != null) {
            AnanUserDetail principal = (AnanUserDetail) userAuthentication.getPrincipal();
            if (principal != null) {
                String oldClientIp = "";
                OAuth2Authentication oldAuthentication = tokenStore.readAuthentication(existingAccessToken);
                if (oldAuthentication != null) {
                    // 获取之前登录IP
                    Authentication oldUserAuthentication = oldAuthentication.getUserAuthentication();
                    // 由于直接通过(AnanUserDetail) userAuthentication.getPrincipal()获取oldPrincipal会和springboot-devtools
                    // 产生ClassCastException,因此改成利用反射来获取字段值
                    // Object oldPrincipal = oldUserAuthentication.getPrincipal();
                    // oldClientIp = ReflectUtil.getValueByField("clientIp",oldPrincipal);
                    // Client client = ReflectUtil.getValueByField("client",oldPrincipal);
                    // oldClientIp = client.getIp();
                    AnanUserDetail oldPrincipal = (AnanUserDetail) oldUserAuthentication.getPrincipal();
                    oldClientIp = oldPrincipal.getAnanClient().getIp();
                }
                // 获取当前登录IP
                String clientIp = Optional.of(principal.getAnanClient().getIp()).orElse("");
                // 不一致则判断为异地登录
                landFall = !clientIp.equalsIgnoreCase(oldClientIp);
                log.debug("之前客户端IP:" + oldClientIp);
                log.debug("当前客户端IP:" + clientIp);
                log.debug("是否异地登录:" + landFall);
            }
        }
        if (existingAccessToken.isExpired() || landFall) {
            if (existingAccessToken.getRefreshToken() != null) {
                refreshToken = existingAccessToken.getRefreshToken();
                // The token store could remove the refresh token when the
                // access token is removed, but we want to
                // be sure...
                tokenStore.removeRefreshToken(refreshToken);
            // refreshToken = null;
            }
            tokenStore.removeAccessToken(existingAccessToken);
        } else {
            // Re-store the access token in case the authentication has changed
            tokenStore.storeAccessToken(existingAccessToken, authentication);
            return existingAccessToken;
        }
    }
    // expired.
    if (refreshToken == null) {
        refreshToken = createRefreshToken(authentication);
    } else // expired.
    if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
        ExpiringOAuth2RefreshToken expiring = (ExpiringOAuth2RefreshToken) refreshToken;
        if (System.currentTimeMillis() > expiring.getExpiration().getTime()) {
            refreshToken = createRefreshToken(authentication);
        }
    }
    OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken);
    tokenStore.storeAccessToken(accessToken, authentication);
    // In case it was modified
    refreshToken = accessToken.getRefreshToken();
    if (refreshToken != null) {
        tokenStore.storeRefreshToken(refreshToken, authentication);
    }
    return accessToken;
}
Also used : OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) AnanUserDetail(top.fosin.anan.cloudresource.dto.AnanUserDetail)

Example 99 with OAuth2RefreshToken

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

the class OAuth2RefreshTokenGenerator method generate.

@Nullable
@Override
public OAuth2RefreshToken generate(OAuth2TokenContext context) {
    if (!OAuth2TokenType.REFRESH_TOKEN.equals(context.getTokenType())) {
        return null;
    }
    Instant issuedAt = Instant.now();
    Instant expiresAt = issuedAt.plus(context.getRegisteredClient().getTokenSettings().getRefreshTokenTimeToLive());
    return new OAuth2RefreshToken(this.refreshTokenGenerator.generateKey(), issuedAt, expiresAt);
}
Also used : OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) Instant(java.time.Instant) Nullable(org.springframework.lang.Nullable)

Example 100 with OAuth2RefreshToken

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

the class OAuth2RefreshTokenGeneratorTests method generateWhenRefreshTokenTypeThenReturnRefreshToken.

@Test
public void generateWhenRefreshTokenTypeThenReturnRefreshToken() {
    RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build();
    // @formatter:off
    OAuth2TokenContext tokenContext = DefaultOAuth2TokenContext.builder().registeredClient(registeredClient).tokenType(OAuth2TokenType.REFRESH_TOKEN).build();
    // @formatter:on
    OAuth2RefreshToken refreshToken = this.tokenGenerator.generate(tokenContext);
    assertThat(refreshToken).isNotNull();
    Instant issuedAt = Instant.now();
    Instant expiresAt = issuedAt.plus(tokenContext.getRegisteredClient().getTokenSettings().getRefreshTokenTimeToLive());
    assertThat(refreshToken.getIssuedAt()).isBetween(issuedAt.minusSeconds(1), issuedAt.plusSeconds(1));
    assertThat(refreshToken.getExpiresAt()).isBetween(expiresAt.minusSeconds(1), expiresAt.plusSeconds(1));
}
Also used : OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) Instant(java.time.Instant) RegisteredClient(org.springframework.security.oauth2.server.authorization.client.RegisteredClient) 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