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

The following examples show how to use org.springframework.security.oauth2.common.OAuth2AccessToken#isExpired() . 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: RefreshTokenFilter.java    From tutorials with MIT License 6 votes vote down vote up
/**
 * Refresh the access and refresh tokens if they are about to expire.
 *
 * @param httpServletRequest  the servlet request holding the current cookies. If no refresh cookie is present,
 *                            then we are out of luck.
 * @param httpServletResponse the servlet response that gets the new set-cookie headers, if they had to be
 *                            refreshed.
 * @return a new request to use downstream that contains the new cookies, if they had to be refreshed.
 * @throws InvalidTokenException if the tokens could not be refreshed.
 */
public HttpServletRequest refreshTokensIfExpiring(HttpServletRequest httpServletRequest, HttpServletResponse
    httpServletResponse) {
    HttpServletRequest newHttpServletRequest = httpServletRequest;
    //get access token from cookie
    Cookie accessTokenCookie = OAuth2CookieHelper.getAccessTokenCookie(httpServletRequest);
    if (mustRefreshToken(accessTokenCookie)) {        //we either have no access token, or it is expired, or it is about to expire
        //get the refresh token cookie and, if present, request new tokens
        Cookie refreshCookie = OAuth2CookieHelper.getRefreshTokenCookie(httpServletRequest);
        if (refreshCookie != null) {
            try {
                newHttpServletRequest = authenticationService.refreshToken(httpServletRequest, httpServletResponse, refreshCookie);
            } catch (HttpClientErrorException ex) {
                throw new UnauthorizedClientException("could not refresh OAuth2 token", ex);
            }
        } else if (accessTokenCookie != null) {
            log.warn("access token found, but no refresh token, stripping them all");
            OAuth2AccessToken token = tokenStore.readAccessToken(accessTokenCookie.getValue());
            if (token.isExpired()) {
                throw new InvalidTokenException("access token has expired, but there's no refresh token");
            }
        }
    }
    return newHttpServletRequest;
}
 
Example 2
Source File: MyOAuth2RestTemplate.java    From springboot-security-wechat with Apache License 2.0 6 votes vote down vote up
public OAuth2AccessToken getAccessToken() throws UserRedirectRequiredException {
    OAuth2AccessToken accessToken = this.context.getAccessToken();
    if(accessToken == null || accessToken.isExpired()) {
        try {
            accessToken = this.acquireAccessToken(this.context);
        } catch (UserRedirectRequiredException var5) {
            this.context.setAccessToken((OAuth2AccessToken)null);
            accessToken = null;
            String stateKey = var5.getStateKey();
            if(stateKey != null) {
                Object stateToPreserve = var5.getStateToPreserve();
                if(stateToPreserve == null) {
                    stateToPreserve = "NONE";
                }

                this.context.setPreservedState(stateKey, stateToPreserve);
            }

            throw var5;
        }
    }

    return accessToken;
}
 
Example 3
Source File: OAuth2FeignRequestInterceptor.java    From spring-cloud-security with Apache License 2.0 6 votes vote down vote up
/**
 * Extract the access token within the request or try to acquire a new one by
 * delegating it to {@link #acquireAccessToken()}.
 * @return valid token
 */
public OAuth2AccessToken getToken() {

	OAuth2AccessToken accessToken = oAuth2ClientContext.getAccessToken();
	if (accessToken == null || accessToken.isExpired()) {
		try {
			accessToken = acquireAccessToken();
		}
		catch (UserRedirectRequiredException e) {
			oAuth2ClientContext.setAccessToken(null);
			String stateKey = e.getStateKey();
			if (stateKey != null) {
				Object stateToPreserve = e.getStateToPreserve();
				if (stateToPreserve == null) {
					stateToPreserve = "NONE";
				}
				oAuth2ClientContext.setPreservedState(stateKey, stateToPreserve);
			}
			throw e;
		}
	}
	return accessToken;
}
 
Example 4
Source File: IntrospectController.java    From platform with Apache License 2.0 6 votes vote down vote up
/**
 * INTROSPECT
 *
 * @param token 凭证
 * @return Map
 */
@Operation(summary = "INTROSPECT")
@ApiResponse(description = "INTROSPECT")
@PostMapping("/introspect")
public Map<String, Object> introspect(@RequestParam("token") String token) {
    OAuth2AccessToken accessToken = this.tokenStore.readAccessToken(token);
    Map<String, Object> attributes = new HashMap<>();
    if (accessToken == null || accessToken.isExpired()) {
        attributes.put("active", false);
        return attributes;
    }

    OAuth2Authentication authentication = this.tokenStore.readAuthentication(token);

    attributes.put("active", true);
    attributes.put("exp", accessToken.getExpiration().getTime());
    attributes.put("scope", String.join(" ", accessToken.getScope()));
    attributes.put("sub", authentication.getName());

    return attributes;
}
 
Example 5
Source File: AuthorizationServerConfiguration.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
@PostMapping("/introspect")
@ResponseBody
public Map<String, Object> introspect(@RequestParam("token") String token) {
	OAuth2AccessToken accessToken = this.tokenStore.readAccessToken(token);
	Map<String, Object> attributes = new HashMap<>();
	if (accessToken == null || accessToken.isExpired()) {
		attributes.put("active", false);
		return attributes;
	}

	OAuth2Authentication authentication = this.tokenStore.readAuthentication(token);

	attributes.put("active", true);
	attributes.put("exp", accessToken.getExpiration().getTime());
	attributes.put("scope", accessToken.getScope().stream().collect(Collectors.joining(" ")));
	attributes.put("sub", authentication.getName());

	return attributes;
}
 
Example 6
Source File: AuthorizationServerConfiguration.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
@PostMapping("/introspect")
@ResponseBody
public Map<String, Object> introspect(@RequestParam("token") String token) {
	OAuth2AccessToken accessToken = this.tokenStore.readAccessToken(token);
	Map<String, Object> attributes = new HashMap<>();
	if (accessToken == null || accessToken.isExpired()) {
		attributes.put("active", false);
		return attributes;
	}

	OAuth2Authentication authentication = this.tokenStore.readAuthentication(token);

	attributes.put("active", true);
	attributes.put("exp", accessToken.getExpiration().getTime());
	attributes.put("scope", accessToken.getScope().stream().collect(Collectors.joining(" ")));
	attributes.put("sub", authentication.getName());

	return attributes;
}
 
Example 7
Source File: AuthorizationServerConfiguration.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
@PostMapping("/introspect")
@ResponseBody
public Map<String, Object> introspect(@RequestParam("token") String token) {
	OAuth2AccessToken accessToken = this.tokenStore.readAccessToken(token);
	Map<String, Object> attributes = new HashMap<>();
	if (accessToken == null || accessToken.isExpired()) {
		attributes.put("active", false);
		return attributes;
	}

	OAuth2Authentication authentication = this.tokenStore.readAuthentication(token);

	attributes.put("active", true);
	attributes.put("exp", accessToken.getExpiration().getTime());
	attributes.put("scope", accessToken.getScope().stream().collect(Collectors.joining(" ")));
	attributes.put("sub", authentication.getName());

	return attributes;
}
 
Example 8
Source File: AuthorizationServerConfiguration.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
@PostMapping("/introspect")
@ResponseBody
public Map<String, Object> introspect(@RequestParam("token") String token) {
	OAuth2AccessToken accessToken = this.tokenStore.readAccessToken(token);
	Map<String, Object> attributes = new HashMap<>();
	if (accessToken == null || accessToken.isExpired()) {
		attributes.put("active", false);
		return attributes;
	}

	OAuth2Authentication authentication = this.tokenStore.readAuthentication(token);

	attributes.put("active", true);
	attributes.put("exp", accessToken.getExpiration().getTime());
	attributes.put("scope", accessToken.getScope().stream().collect(Collectors.joining(" ")));
	attributes.put("sub", authentication.getName());

	return attributes;
}
 
Example 9
Source File: AuthorizationServerConfiguration.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
@PostMapping("/introspect")
@ResponseBody
public Map<String, Object> introspect(@RequestParam("token") String token) {
	OAuth2AccessToken accessToken = this.tokenStore.readAccessToken(token);
	Map<String, Object> attributes = new HashMap<>();
	if (accessToken == null || accessToken.isExpired()) {
		attributes.put("active", false);
		return attributes;
	}

	OAuth2Authentication authentication = this.tokenStore.readAuthentication(token);

	attributes.put("active", true);
	attributes.put("exp", accessToken.getExpiration().getTime());
	attributes.put("scope", accessToken.getScope().stream().collect(Collectors.joining(" ")));
	attributes.put("sub", authentication.getName());

	return attributes;
}
 
Example 10
Source File: AuthorizationServerConfiguration.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
@PostMapping("/introspect")
@ResponseBody
public Map<String, Object> introspect(@RequestParam("token") String token) {
	OAuth2AccessToken accessToken = this.tokenStore.readAccessToken(token);
	Map<String, Object> attributes = new HashMap<>();
	if (accessToken == null || accessToken.isExpired()) {
		attributes.put("active", false);
		return attributes;
	}

	OAuth2Authentication authentication = this.tokenStore.readAuthentication(token);

	attributes.put("active", true);
	attributes.put("exp", accessToken.getExpiration().getTime());
	attributes.put("scope", accessToken.getScope().stream().collect(Collectors.joining(" ")));
	attributes.put("sub", authentication.getName());

	return attributes;
}
 
Example 11
Source File: AuthorizationServerConfiguration.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
@PostMapping("/introspect")
@ResponseBody
public Map<String, Object> introspect(@RequestParam("token") String token) {
	OAuth2AccessToken accessToken = this.tokenStore.readAccessToken(token);
	Map<String, Object> attributes = new HashMap<>();
	if (accessToken == null || accessToken.isExpired()) {
		attributes.put("active", false);
		return attributes;
	}

	OAuth2Authentication authentication = this.tokenStore.readAuthentication(token);

	attributes.put("active", true);
	attributes.put("exp", accessToken.getExpiration().getTime());
	attributes.put("scope", accessToken.getScope().stream().collect(Collectors.joining(" ")));
	attributes.put("sub", authentication.getName());

	return attributes;
}
 
Example 12
Source File: AuthorizationServerConfiguration.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
@PostMapping("/introspect")
@ResponseBody
public Map<String, Object> introspect(@RequestParam("token") String token) {
	OAuth2AccessToken accessToken = this.tokenStore.readAccessToken(token);
	Map<String, Object> attributes = new HashMap<>();
	if (accessToken == null || accessToken.isExpired()) {
		attributes.put("active", false);
		return attributes;
	}

	OAuth2Authentication authentication = this.tokenStore.readAuthentication(token);

	attributes.put("active", true);
	attributes.put("exp", accessToken.getExpiration().getTime());
	attributes.put("scope", accessToken.getScope().stream().collect(Collectors.joining(" ")));
	attributes.put("sub", authentication.getName());

	return attributes;
}
 
Example 13
Source File: RefreshTokenFilter.java    From cubeai with Apache License 2.0 5 votes vote down vote up
/**
 * Check if we must refresh the access token.
 * We must refresh it, if we either have no access token, or it is expired, or it is about to expire.
 *
 * @param accessTokenCookie the current access token.
 * @return true, if it must be refreshed; false, otherwise.
 */
private boolean mustRefreshToken(Cookie accessTokenCookie) {
    if (accessTokenCookie == null) {
        return true;
    }
    OAuth2AccessToken token = tokenStore.readAccessToken(accessTokenCookie.getValue());
    //check if token is expired or about to expire
    if (token.isExpired() || token.getExpiresIn() < REFRESH_WINDOW_SECS) {
        return true;
    }
    return false;       //access token is still fine
}
 
Example 14
Source File: YamiTokenServices.java    From mall4j with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public OAuth2Authentication loadAuthentication(String accessTokenValue) throws AuthenticationException,
        InvalidTokenException {
    OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue);
    if (accessToken == null) {
        throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
    }
    else if (accessToken.isExpired()) {
        tokenStore.removeAccessToken(accessToken);
        throw new InvalidTokenException("Access token expired: " + accessTokenValue);
    }

    OAuth2Authentication result = tokenStore.readAuthentication(accessToken);
    if (result == null) {
        // in case of race condition
        throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
    }
    if (clientDetailsService != null) {
        String clientId = result.getOAuth2Request().getClientId();
        try {
            clientDetailsService.loadClientByClientId(clientId);
        }
        catch (ClientRegistrationException e) {
            throw new InvalidTokenException("Client not valid: " + clientId, e);
        }
    }
    return result;
}
 
Example 15
Source File: RefreshTokenFilter.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Check if we must refresh the access token.
 * We must refresh it, if we either have no access token, or it is expired, or it is about to expire.
 *
 * @param accessTokenCookie the current access token.
 * @return true, if it must be refreshed; false, otherwise.
 */
private boolean mustRefreshToken(Cookie accessTokenCookie) {
    if (accessTokenCookie == null) {
        return true;
    }
    OAuth2AccessToken token = tokenStore.readAccessToken(accessTokenCookie.getValue());
    //check if token is expired or about to expire
    if (token.isExpired() || token.getExpiresIn() < REFRESH_WINDOW_SECS) {
        return true;
    }
    return false;       //access token is still fine
}
 
Example 16
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 17
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 18
Source File: EntandoOauth2Interceptor.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void validateToken(HttpServletRequest request, String accessToken, final OAuth2AccessToken token) {
    if (null == token) {
        throw new EntandoTokenException("no token found", request, "guest");
    } else if (!token.getValue().equals(accessToken)) {
        throw new EntandoTokenException("invalid token", request, "guest");
    } else if (token.isExpired()) {
        throw new EntandoTokenException("expired token", request, "guest");
    }
}
 
Example 19
Source File: OAuth2TokenDAO.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public List<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String username) {
    if (StringUtils.isBlank(clientId) && StringUtils.isBlank(username)) {
        throw new RuntimeException("clientId and username cannot both be null");
    }
    FieldSearchFilter expirationFilter = new FieldSearchFilter("expiresin");
    expirationFilter.setOrder(FieldSearchFilter.Order.ASC);
    FieldSearchFilter[] filters = {expirationFilter};
    if (!StringUtils.isBlank(clientId)) {
        FieldSearchFilter clientIdFilter = new FieldSearchFilter("clientid", clientId, true);
        filters = ArrayUtils.add(filters, clientIdFilter);
    }
    if (!StringUtils.isBlank(username)) {
        FieldSearchFilter usernameFilter = new FieldSearchFilter("localuser", username, true);
        filters = ArrayUtils.add(filters, usernameFilter);
    }
    List<OAuth2AccessToken> accessTokens = new ArrayList<>();
    List<String> tokens = super.searchId(filters);
    if (tokens.isEmpty()) {
        return accessTokens;
    }
    Connection conn = null;
    try {
        conn = this.getConnection();
        for (String token : tokens) {
            OAuth2AccessToken accessToken = this.getAccessToken(token, conn);
            if (!accessToken.isExpired()) {
                accessTokens.add(accessToken);
            }
        }
    } catch (Exception t) {
        logger.error("Error while loading tokens", t);
        throw new RuntimeException("Error while loading tokens", t);
    } finally {
        this.closeConnection(conn);
    }
    return accessTokens;
}
 
Example 20
Source File: OAuth2AuthorizationServerConfig.java    From NFVO with Apache License 2.0 3 votes vote down vote up
/**
 * Validates an image token against an image ID. If the token is able to grant access to the image
 * file, this method returns true otherwise false.
 *
 * @param token the token passed to the REST API
 * @param imageId ID of the NFVImage
 * @return
 */
public boolean validateImageToken(String token, String imageId) {
  OAuth2AccessToken imageToken = imageTokenServices.readAccessToken(token);
  if (imageToken == null || imageToken.isExpired() || !imageToken.getScope().contains(imageId))
    return false;
  return true;
}