Java Code Examples for org.springframework.security.oauth2.common.OAuth2AccessToken#getRefreshToken()

The following examples show how to use org.springframework.security.oauth2.common.OAuth2AccessToken#getRefreshToken() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OauthLogoutHandler.java    From open-capacity-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
	Assert.notNull(tokenStore, "tokenStore must be set");
	String token = extractToken(request);
	if(token!=null || !"".equals(token)){
		OAuth2AccessToken existingAccessToken = tokenStore.readAccessToken(token);
		OAuth2RefreshToken refreshToken;
		if (existingAccessToken != null) {
			if (existingAccessToken.getRefreshToken() != null) {
				logger.info("remove refreshToken!", existingAccessToken.getRefreshToken());
				refreshToken = existingAccessToken.getRefreshToken();
				tokenStore.removeRefreshToken(refreshToken);
			}
			logger.info("remove existingAccessToken!", existingAccessToken);
			tokenStore.removeAccessToken(existingAccessToken);
		}
		return;
	}

}
 
Example 2
Source File: CustomLogoutHandler.java    From microservice-integration with MIT License 6 votes vote down vote up
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    Assert.notNull(tokenStore, "tokenStore must be set");
    String token = request.getHeader("Authorization");
    Assert.hasText(token, "token must be set");
    if (isJwtBearerToken(token)) {
        token = token.substring(6);
        OAuth2AccessToken existingAccessToken = tokenStore.readAccessToken(token);
        OAuth2RefreshToken refreshToken;
        if (existingAccessToken != null) {
            if (existingAccessToken.getRefreshToken() != null) {
                LOGGER.info("remove refreshToken!", existingAccessToken.getRefreshToken());
                refreshToken = existingAccessToken.getRefreshToken();
                tokenStore.removeRefreshToken(refreshToken);
            }
            LOGGER.info("remove existingAccessToken!", existingAccessToken);
            tokenStore.removeAccessToken(existingAccessToken);
        }
        return;
    } else {
        throw new BadClientCredentialsException();
    }

}
 
Example 3
Source File: CustomLogoutHandler.java    From Auth-service with MIT License 6 votes vote down vote up
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    Assert.notNull(tokenStore, "tokenStore must be set");
    String token = request.getHeader("Authorization");
    Assert.hasText(token, "token must be set");
    if (isJwtBearerToken(token)) {
        token = token.substring(6).trim();
        OAuth2AccessToken existingAccessToken = tokenStore.readAccessToken(token);
        OAuth2RefreshToken refreshToken;
        if (existingAccessToken != null) {
            if (existingAccessToken.getRefreshToken() != null) {
                LOGGER.info("remove refreshToken!", existingAccessToken.getRefreshToken());
                refreshToken = existingAccessToken.getRefreshToken();
                tokenStore.removeRefreshToken(refreshToken);
            }
            LOGGER.info("remove existingAccessToken!", existingAccessToken);
            tokenStore.removeAccessToken(existingAccessToken);
        }
        return;
    } else {
        throw new BadClientCredentialsException();
    }

}
 
Example 4
Source File: CustomJwtTokenEnhancer.java    From fast-family-master with Apache License 2.0 6 votes vote down vote up
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
    if (oAuth2AccessToken instanceof DefaultOAuth2AccessToken) {
        DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) oAuth2AccessToken;
        String clientId = oAuth2Authentication.getOAuth2Request().getClientId();
        Date expiration = oAuth2AccessToken.getExpiration();
        String createToken = createToken(clientId, expiration);
        token.setValue(createToken);
        OAuth2RefreshToken refreshToken = oAuth2AccessToken.getRefreshToken();
        if (refreshToken instanceof DefaultOAuth2AccessToken) {
            token.setRefreshToken(new DefaultOAuth2RefreshToken(createToken(clientId, expiration)));
        }
        Map<String, Object> additionalInformation = new HashMap<>();
        additionalInformation.put("client_id", oAuth2Authentication.getOAuth2Request().getClientId());
        token.setAdditionalInformation(additionalInformation);
        return token;
    }
    return oAuth2AccessToken;
}
 
Example 5
Source File: OAuth2CookieHelper.java    From cubeai with Apache License 2.0 6 votes vote down vote up
/**
 * Create cookies using the provided values.
 *
 * @param request     the request we are handling.
 * @param accessToken the access token and enclosed refresh token for our cookies.
 * @param rememberMe  whether the user had originally checked "remember me".
 * @param result      will get the resulting cookies set.
 */
public void createCookies(HttpServletRequest request, OAuth2AccessToken accessToken, boolean rememberMe,
                          OAuth2Cookies result) {
    String domain = getCookieDomain(request);
    log.debug("creating cookies for domain {}", domain);
    Cookie accessTokenCookie = new Cookie(ACCESS_TOKEN_COOKIE, accessToken.getValue());
    setCookieProperties(accessTokenCookie, request.isSecure(), domain);
    log.debug("created access token cookie '{}'", accessTokenCookie.getName());

    OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
    Cookie refreshTokenCookie = createRefreshTokenCookie(refreshToken, rememberMe);
    setCookieProperties(refreshTokenCookie, request.isSecure(), domain);
    log.debug("created refresh token cookie '{}', age: {}", refreshTokenCookie.getName(), refreshTokenCookie
        .getMaxAge());

    result.setCookies(accessTokenCookie, refreshTokenCookie);
}
 
Example 6
Source File: HomeController.java    From sophia_scaffolding with Apache License 2.0 6 votes vote down vote up
/**
 * 清除token(注销登录)
 */
@SysLog("登出")
@DeleteMapping("/logout")
@ApiOperation(value = "登出")
public ApiResponse logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) {
    if (StringUtils.isBlank(authHeader)) {
        return fail("退出失败,token 为空");
    }
    //注销当前用户
    String tokenValue = authHeader.replace(OAuth2AccessToken.BEARER_TYPE, StringUtils.EMPTY).trim();
    OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
    tokenStore.removeAccessToken(accessToken);
    OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
    tokenStore.removeRefreshToken(refreshToken);
    return success("注销成功");
}
 
Example 7
Source File: OauthLogoutHandler.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
	Assert.notNull(tokenStore, "tokenStore must be set");
	String token = request.getParameter("token");
	if (StrUtil.isEmpty(token)) {
		token = AuthUtils.extractToken(request);
	}
	if(StrUtil.isNotEmpty(token)){
		OAuth2AccessToken existingAccessToken = tokenStore.readAccessToken(token);
		OAuth2RefreshToken refreshToken;
		if (existingAccessToken != null) {
			if (existingAccessToken.getRefreshToken() != null) {
				log.info("remove refreshToken!", existingAccessToken.getRefreshToken());
				refreshToken = existingAccessToken.getRefreshToken();
				tokenStore.removeRefreshToken(refreshToken);
			}
			log.info("remove existingAccessToken!", existingAccessToken);
			tokenStore.removeAccessToken(existingAccessToken);
		}
	}
}
 
Example 8
Source File: GoogleFitShim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(
        OAuth2ProtectedResourceDetails resource,
        OAuth2RefreshToken refreshToken, AccessTokenRequest request)
        throws UserRedirectRequiredException,
        OAuth2AccessDeniedException {

    OAuth2AccessToken accessToken = super.refreshAccessToken(resource, refreshToken, request);
    // Google does not replace refresh tokens, so we need to hold on to the existing refresh token...
    if (accessToken.getRefreshToken() == null) {
        ((DefaultOAuth2AccessToken) accessToken).setRefreshToken(refreshToken);
    }
    return accessToken;
}
 
Example 9
Source File: GsonSerializerOAuth2AccessToken.java    From NFVO with Apache License 2.0 5 votes vote down vote up
@Override
public JsonElement serialize(
    OAuth2AccessToken src, Type typeOfSrc, JsonSerializationContext context) {
  JsonObject jsonObject = new JsonObject();
  jsonObject.addProperty(OAuth2AccessToken.ACCESS_TOKEN, src.getValue());
  // back compatibility for dashboard
  jsonObject.addProperty("value", src.getValue());

  jsonObject.addProperty(OAuth2AccessToken.TOKEN_TYPE, src.getTokenType());

  OAuth2RefreshToken refreshToken = src.getRefreshToken();
  if (refreshToken != null) {
    jsonObject.addProperty(OAuth2AccessToken.REFRESH_TOKEN, refreshToken.getValue());
  }
  Date expiration = src.getExpiration();
  if (expiration != null) {
    long now = System.currentTimeMillis();
    jsonObject.add(
        OAuth2AccessToken.EXPIRES_IN, new JsonPrimitive((expiration.getTime() - now) / 1000));
  }

  Set<String> scope = src.getScope();

  if (scope != null && !scope.isEmpty()) {
    StringBuilder scopes = new StringBuilder();
    for (String s : scope) {
      Assert.hasLength(s, "Scopes cannot be null or empty. Got " + scope + "");
      scopes.append(s);
      scopes.append(" ");
    }

    jsonObject.addProperty(OAuth2AccessToken.SCOPE, scopes.substring(0, scopes.length() - 1));
  }

  return jsonObject;
}
 
Example 10
Source File: YamiTokenServices.java    From mall4j with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public boolean revokeToken(String tokenValue) {
    OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
    if (accessToken == null) {
        return false;
    }
    if (accessToken.getRefreshToken() != null) {
        tokenStore.removeRefreshToken(accessToken.getRefreshToken());
    }
    tokenStore.removeAccessToken(accessToken);
    return true;
}
 
Example 11
Source File: PigRedisTokenStore.java    From pig with MIT License 5 votes vote down vote up
@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {

    this.redisTemplate.opsForValue().set(ACCESS + token.getValue(), token);
    this.redisTemplate.opsForValue().set(AUTH + token.getValue(), authentication);
    this.redisTemplate.opsForValue().set(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication), token);
    if (!authentication.isClientOnly()) {
        redisTemplate.opsForList().rightPush(UNAME_TO_ACCESS + getApprovalKey(authentication), token);
    }

    redisTemplate.opsForList().rightPush(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), token);

    if (token.getExpiration() != null) {

        int seconds = token.getExpiresIn();
        redisTemplate.expire(ACCESS + token.getValue(), seconds, TimeUnit.SECONDS);
        redisTemplate.expire(AUTH + token.getValue(), seconds, TimeUnit.SECONDS);

        redisTemplate.expire(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication), seconds, TimeUnit.SECONDS);
        redisTemplate.expire(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId(), seconds, TimeUnit.SECONDS);
        redisTemplate.expire(UNAME_TO_ACCESS + getApprovalKey(authentication), seconds, TimeUnit.SECONDS);
    }
    if (token.getRefreshToken() != null && token.getRefreshToken().getValue() != null) {
        this.redisTemplate.opsForValue().set(REFRESH_TO_ACCESS + token.getRefreshToken().getValue(), token.getValue());
        this.redisTemplate.opsForValue().set(ACCESS_TO_REFRESH + token.getValue(), token.getRefreshToken().getValue());
    }
}
 
Example 12
Source File: _OAuth2AuthenticationAccessToken.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
@PersistenceConstructor
public OAuth2AuthenticationAccessToken(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication authentication, String authenticationId) {
    this.id = UUID.randomUUID().toString();
    this.tokenId = oAuth2AccessToken.getValue();
    this.oAuth2AccessToken = oAuth2AccessToken;
    this.authenticationId = authenticationId;
    this.userName = authentication.getName();
    this.clientId = authentication.getOAuth2Request().getClientId();
    this.authentication = authentication;
    if(oAuth2AccessToken.getRefreshToken() != null) {
        this.refreshToken = oAuth2AccessToken.getRefreshToken().getValue();
    }
}
 
Example 13
Source File: TokenService.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
/**
 * Chooses a token among all tokens for this user in the token store.
 * 
 * @param userName the username
 * @return the chosen token, or null if no token was found
 */
public OAuth2AccessToken getToken(String userName) {
    OAuth2AccessToken token = null;
    Collection<OAuth2AccessToken> tokens = tokenStore.findTokensByUserName(userName);
    for (OAuth2AccessToken tokenx : tokens) {
        // If a token is already found, overwrite it if the new token:
        // 1) has a refresh token, and the current token hasn't, or
        // 2) expires later than the current token
        if (token == null || ((tokenx.getRefreshToken() != null) && (token.getRefreshToken() == null))
            || (tokenx.getExpiresIn() > token.getExpiresIn())) {
            token = tokenx;
        }
    }
    return token;
}
 
Example 14
Source File: CloudControllerClientProvider.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
private OAuth2AccessToken getValidToken(String userName) {
    OAuth2AccessToken token = tokenService.getToken(userName);
    if (token == null) {
        throw new SLException(Messages.NO_VALID_TOKEN_FOUND, userName);
    }

    if (token.isExpired() && token.getRefreshToken() == null) {
        tokenService.removeToken(token);
        throw new SLException(Messages.TOKEN_EXPIRED, userName);
    }

    return token;
}
 
Example 15
Source File: CustomTokenServices.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2Authentication loadAuthentication(String tokenString) {

    // Get an access token for the specified token string
    OAuth2AccessToken token = readAccessToken(tokenString);

    // Check if a valid access token has been obtained
    if (token == null) {
        logToAuditLogAndThrow("Invalid access token");
    }

    // Check if the token has expired and there is no refresh token
    if (token.isExpired() && token.getRefreshToken() == null) {
        tokenStore.removeAccessToken(token);
        logToAuditLogAndThrow(MessageFormat.format("The access token has expired on {0}", token.getExpiration()));
    }

    // Check if an authentication for this token already exists in the token store
    OAuth2Authentication auth = tokenStore.readAuthentication(token);
    if (auth == null) {
        // Create an authentication for the token and store it in the token store
        TokenProperties tokenProperties = TokenProperties.fromToken(token);
        auth = SecurityUtil.createAuthentication(tokenProperties.getClientId(), token.getScope(), SecurityUtil.getTokenUserInfo(token));
        try {
            LOGGER.info(MessageFormat.format(Messages.STORING_TOKEN_FOR_USER_0_WITH_EXPIRATION_TIME_1, tokenProperties.getUserName(),
                                             token.getExpiresIn()));
            tokenStore.storeAccessToken(token, auth);
        } catch (DataIntegrityViolationException e) {
            LOGGER.debug(Messages.ERROR_STORING_TOKEN_DUE_TO_INTEGRITY_VIOLATION, e);
            // Ignoring the exception as the token and authentication are already persisted by another client.
        }
    }

    return auth;
}
 
Example 16
Source File: MongoTokenStore.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
    LOG.debug("Call storeAccessToken, token = {}, authentication = {}", token, authentication);
    String refreshToken = token.getRefreshToken() != null ? token.getRefreshToken().getValue() : null;

    AccessToken accessToken = tokenRepository.findOne(extractTokenKey(token.getValue()));
    if (accessToken != null) {
        accessToken.token(token);
        accessToken.setAuthenticationId(authenticationKeyGenerator.extractKey(authentication));
        accessToken.authentication(authentication);
        accessToken.setRefreshToken(extractTokenKey(refreshToken));
    } else {
        accessToken = AccessToken.builder()
                .tokenId(extractTokenKey(token.getValue()))
                .authenticationId(authenticationKeyGenerator.extractKey(authentication))
                .username(authentication.isClientOnly() ? null : authentication.getName())
                .clientId(authentication.getOAuth2Request().getClientId())
                .refreshToken(extractTokenKey(refreshToken))
                .build();

        accessToken.token(token);
        accessToken.authentication(authentication);
    }
    tokenRepository.save(accessToken);
    Random random = new Random();
    int delayTime = random.nextInt(MAX_DELAY_TIME - MIN_DELAY_TIME) + MIN_DELAY_TIME;
    try {
        Thread.sleep(delayTime);
    } catch (InterruptedException e) {
        LOG.error("Error on login silence timer...");
    }
}
 
Example 17
Source File: OAuth2Controller.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
/**
 * 移除access_token和refresh_token
 * 
 * @param access_token
 */
@ApiOperation(value = "移除token")
@PostMapping(value = "/oauth/remove/token", params = "access_token")
public void removeToken(String access_token) {

	// 拿到当前用户信息
	Authentication user = SecurityContextHolder.getContext().getAuthentication();

	if (user != null) {
		if (user instanceof OAuth2Authentication) {
			Authentication athentication = (Authentication) user;
			OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) athentication.getDetails();
		}

	}
	OAuth2AccessToken accessToken = tokenStore.readAccessToken(access_token);
	if (accessToken != null) {
		// 移除access_token
		tokenStore.removeAccessToken(accessToken);

		// 移除refresh_token
		if (accessToken.getRefreshToken() != null) {
			tokenStore.removeRefreshToken(accessToken.getRefreshToken());
		}

	}
}
 
Example 18
Source File: YamiTokenServices.java    From mall4j with GNU Affero General Public License v3.0 4 votes vote down vote up
@Transactional(rollbackFor = Exception.class)
    @Override
    public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) {

        OAuth2AccessToken existingAccessToken = tokenStore.getAccessToken(authentication);
        OAuth2RefreshToken refreshToken = null;
        // 如果有token,直接删除,更新token,避免出现缓存问题
//        if (existingAccessToken != null) {
//            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);
//            }
//            tokenStore.removeAccessToken(existingAccessToken);
//
//        }

        // Only create a new refresh token if there wasn't an existing one
        // associated with an expired access token.
        // Clients might be holding existing refresh tokens, so we re-use it in
        // the case that the old access token
        // expired.
        if (refreshToken == null) {
            refreshToken = createRefreshToken(authentication);
        }
        // But the refresh token itself might need to be re-issued if it has
        // expired.
        else 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;

    }
 
Example 19
Source File: MyAccessTokenProviderChain.java    From springboot-security-wechat with Apache License 2.0 4 votes vote down vote up
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 && !resource.isClientOnly()) {
        throw new InsufficientAuthenticationException("Authentication is required to obtain an access token (anonymous not allowed)");
    } else {
        if(resource.isClientOnly() || auth != null && auth.isAuthenticated()) {
            existingToken = request.getExistingToken();
            if(existingToken == null && this.clientTokenServices != null) {
                existingToken = this.clientTokenServices.getAccessToken(resource, auth);
            }

            if(existingToken != null) {
                if(existingToken.isExpired()) {
                    if(this.clientTokenServices != null) {
                        this.clientTokenServices.removeAccessToken(resource, auth);
                    }

                    OAuth2RefreshToken refreshToken = existingToken.getRefreshToken();
                    if(refreshToken != null) {
                        accessToken = this.refreshAccessToken(resource, refreshToken, request);
                    }
                } else {
                    accessToken = existingToken;
                }
            }
        }

        if(accessToken == null) {
            accessToken = this.obtainNewAccessTokenInternal(resource, request);
            if(accessToken == null) {
                System.out.println("An OAuth 2 access token must be obtained or an exception thrown.");
                throw new IllegalStateException("An OAuth 2 access token must be obtained or an exception thrown.");
            }
        }

        if(this.clientTokenServices != null && (resource.isClientOnly() || auth != null && auth.isAuthenticated())) {
            this.clientTokenServices.saveAccessToken(resource, auth, accessToken);
        }

        return accessToken;
    }
}
 
Example 20
Source File: ClientFactory.java    From multiapps-controller with Apache License 2.0 4 votes vote down vote up
private static CloudCredentials createCredentials(OAuth2AccessToken token) {
    boolean refreshable = (token.getRefreshToken() != null);
    return new CloudCredentials(token, refreshable);
}