本文整理汇总了Java中org.springframework.security.oauth2.common.exceptions.InvalidTokenException类的典型用法代码示例。如果您正苦于以下问题:Java InvalidTokenException类的具体用法?Java InvalidTokenException怎么用?Java InvalidTokenException使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
InvalidTokenException类属于org.springframework.security.oauth2.common.exceptions包,在下文中一共展示了InvalidTokenException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: loadAuthentication
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; //导入依赖的package包/类
@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.substring(0,200));
}
OAuth2Authentication result = tokenStore.readAuthentication(accessToken);
if (result == null) {
// in case of race condition
throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
}
return result;
}
示例2: loadAuthentication
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; //导入依赖的package包/类
public OAuth2Authentication loadAuthentication(String accessToken,
String ip) throws AuthenticationException, InvalidTokenException {
Map<String, Object> map = this.getMap(this.userInfoEndpointUrl, accessToken);
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println("key == " + entry.getKey() + " value == " + entry.getValue());
}
if(map.containsKey("error")) {
if(this.logger.isDebugEnabled()) {
this.logger.debug("userinfo returned error: " + map.get("error"));
}
throw new InvalidTokenException(accessToken);
} else {
return this.extractAuthentication(map, ip);
}
}
示例3: handleException
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; //导入依赖的package包/类
@ExceptionHandler(InvalidTokenException.class)
public ResponseEntity<OAuth2Exception> handleException(Exception e) throws Exception {
logger.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage());
// This isn't an oauth resource, so we don't want to send an
// unauthorized code here. The client has already authenticated
// successfully with basic auth and should just
// get back the invalid token error.
@SuppressWarnings("serial")
InvalidTokenException e400 = new InvalidTokenException(e.getMessage()) {
@Override
public int getHttpErrorCode() {
return 400;
}
};
return exceptionTranslator.translate(e400);
}
示例4: loadAuthentication
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; //导入依赖的package包/类
@Override
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException {
GitHubClient gitHubClient = GitHubClient.withAccessToken(accessToken);
UserResource gitHubUser = gitHubClient.getUser();
List<String> allowedOrganizations = ofNullable(loginDetails.get().getRestrictions())
.flatMap(restrictions -> ofNullable(restrictions.get("organizations")))
.map(it -> Splitter.on(",").omitEmptyStrings().splitToList(it))
.orElse(emptyList());
if (!allowedOrganizations.isEmpty()) {
boolean assignedToOrganization = gitHubClient.getUserOrganizations(gitHubUser).stream().map(userOrg -> userOrg.login)
.anyMatch(allowedOrganizations::contains);
if (!assignedToOrganization) {
throw new InsufficientOrganizationException("User '" + gitHubUser.login + "' does not belong to allowed GitHUB organization");
}
}
User user = replicator.replicateUser(gitHubUser, gitHubClient);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getId(), "N/A",
AuthUtils.AS_AUTHORITIES.apply(user.getRole()));
Map<String, Serializable> extensionProperties = Collections.singletonMap("upstream_token", accessToken);
OAuth2Request request = new OAuth2Request(null, loginDetails.get().getClientId(), null, true, null, null, null, null, extensionProperties);
return new OAuth2Authentication(request, token);
}
示例5: loadAuthentication
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; //导入依赖的package包/类
@Override
public OAuth2Authentication loadAuthentication(String accessToken)
throws AuthenticationException, InvalidTokenException {
OAuth2Authentication authentication = super.loadAuthentication(accessToken);
OAuth2Request request = authentication.getOAuth2Request();
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.class.cast(authentication.getUserAuthentication());
Map<String, Object> map = Map.class.cast(token.getDetails());
String id = map.getOrDefault("id", "").toString();
Triple<OAuthSource, String, Integer> principal = Triple.of(source, id, null);
Object credentials = token.getCredentials();
List<GrantedAuthority> authorities = Lists.newArrayList(token.getAuthorities());
OAuthUser user = this.repository.findBySourceAndId(source, id);
if (user != null) {
Assert.state(user.getUser() != null);
principal = Triple.of(source, id, user.getUser().getId());
authorities.add(new SimpleGrantedAuthority("ROLE_SU"));
}
token = new UsernamePasswordAuthenticationToken(principal, credentials, authorities);
token.setDetails(map);
return new OAuth2Authentication(request, token);
}
示例6: loadAuthentication
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; //导入依赖的package包/类
@Override
public OAuth2Authentication loadAuthentication(final String accessToken) throws AuthenticationException,
InvalidTokenException {
if (!StringUtils.hasText(accessToken)) {
throw new InvalidTokenException("AccessToken should not be 'null', 'empty' or 'whitespace'");
}
if (NONE.equalsIgnoreCase(accessToken)) {
throw new InvalidTokenException("AccessToken should not be 'None'");
}
if (accessToken.length() < 30) {
throw new InvalidTokenException("AccessToken should have a length of 30 at least ");
}
return super.loadAuthentication(accessToken);
}
示例7: loadAuthentication
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; //导入依赖的package包/类
@Override
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException {
CachedOAuth2Authentication cachedAuthentication = authentications.get(accessToken);
long now = System.currentTimeMillis();
if (cachedAuthentication != null && cachedAuthentication.timestamp + duration > now) {
LOG.debug("Returning OAuth2Authentication from cache {}", cachedAuthentication.authentication);
return cachedAuthentication.authentication;
}
OAuth2Authentication oAuth2Authentication = tokenServices.loadAuthentication(accessToken);
//will not happen, but just to ensure this does not cause memory problems
int size = authentications.size();
if (size < 10000) {
LOG.debug("Putting OAuth2Authentication in cache {} current size: {}", oAuth2Authentication, size + 1);
authentications.put(accessToken, new CachedOAuth2Authentication(now, oAuth2Authentication));
}
return oAuth2Authentication;
}
示例8: preValidate
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; //导入依赖的package包/类
private void preValidate(SignedJWT jwtToken) {
if (JwtUtils.isJtwTokenExpired(jwtToken)) {
throw new InvalidTokenException("access token is expired");
}
String issuer = JwtUtils.getIssuer(jwtToken);
ServerConfiguration serverConfiguration = oauth2ConfigurationsService
.getServerConfiguration(issuer);
JWTSigningAndValidationService validationService = Optional
.ofNullable(validationServices.getValidator(serverConfiguration.getJwksUri()))
.orElseThrow(() -> new AuthorizationServiceException(String
.format("Couldn't retrive validator for issuer %s", issuer)));
if (!validationService.validateSignature(jwtToken)) {
throw new InvalidTokenException("access token has an invalid signature");
}
}
示例9: authenticate
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; //导入依赖的package包/类
/**
* Expects the incoming authentication request to have a principal value that is an access token value (e.g. from an
* authorization header) .Loads an authentication from the {@link ResourceServerTokenServices} and checks that the
* resource id is contained in the {@link AuthorizationRequest} (if one is specified). Also copies authentication
* details over from the input to the output (e.g. typically so that the access token value and request details can
* be reported later).
*
* @param authentication an authentication request containing an access token value as the principal
* @return an {@link OAuth2Authentication}
*
* @see org.springframework.security.authentication.AuthenticationManager#authenticate(org.springframework.security.core.Authentication)
*/
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String token = (String) authentication.getPrincipal();
OAuth2Authentication auth = tokenServices.loadAuthentication(token);
if (auth == null) {
throw new InvalidTokenException("Invalid token: " + token);
}
Collection<String> resourceIds = auth.getOAuth2Request().getResourceIds();
if (resourceId != null && resourceIds != null && !resourceIds.isEmpty() && !resourceIds.contains(resourceId)) {
throw new OAuth2AccessDeniedException("Invalid token does not contain resource id (" + resourceId + ")");
}
auth.setDetails(authentication.getDetails());
return auth;
}
示例10: loadAuthentication
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; //导入依赖的package包/类
public OAuth2Authentication loadAuthentication(String accessTokenValue)
throws AuthenticationException {
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);
return result;
}
示例11: decode
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; //导入依赖的package包/类
protected Map<String, Object> decode(String token) {
Jwt jwt = JwtHelper.decodeAndVerify(token, verifier);
String content = jwt.getClaims();
try {
@SuppressWarnings("unchecked")
Map<String, Object> map = objectMapper.readValue(content, Map.class);
return map;
}
catch (Exception e) {
throw new InvalidTokenException("Cannot convert access token to JSON", e);
}
}
示例12: loadAuthentication
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; //导入依赖的package包/类
public Map<String, Object> loadAuthentication(String accessToken, String clientSecret) throws AuthenticationException, InvalidTokenException {
MultivaluedMap<String, String> formData = new MultivaluedHashMap<>();
String tokenName = "token";
formData.add(tokenName, accessToken);
MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
headers.add("Authorization", "Basic " + Base64.encodeBase64String((clientId + ':' + clientSecret).getBytes()));
Map<String, Object> response;
try {
response = checkTokenWebTarget.request().accept(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.headers(headers).post(Entity.form(formData), Map.class);
} catch (BadRequestException ex) {
LOGGER.warn(String.format("Token check failed for access token: '%s'.", accessToken), ex);
throw new InvalidTokenException(accessToken);
}
if (response.containsKey("error")) {
throw new InvalidTokenException(accessToken);
}
Assert.state(response.containsKey("client_id"), "Client id must be present in response from auth server");
return response;
}
示例13: refreshTokensIfExpiring
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; //导入依赖的package包/类
/**
* 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;
}
示例14: decode
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; //导入依赖的package包/类
/**
* Try to decode the token with the current public key.
* If it fails, contact the OAuth2 server to get a new public key, then try again.
* We might not have fetched it in the first place or it might have changed.
*
* @param token the JWT token to decode.
* @return the resulting claims.
* @throws InvalidTokenException if we cannot decode the token.
*/
@Override
protected Map<String, Object> decode(String token) {
try {
//check if our public key and thus SignatureVerifier have expired
long ttl = oAuth2Properties.getSignatureVerification().getTtl();
if (ttl > 0 && System.currentTimeMillis() - lastKeyFetchTimestamp > ttl) {
throw new InvalidTokenException("public key expired");
}
return super.decode(token);
} catch (InvalidTokenException ex) {
if (tryCreateSignatureVerifier()) {
return super.decode(token);
}
throw ex;
}
}
示例15: loadAuthentication
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; //导入依赖的package包/类
@Override
public OAuth2Authentication loadAuthentication(String accessToken)
throws AuthenticationException, InvalidTokenException {
AccessGrant accessGrant = new AccessGrant(accessToken);
Connection<?> connection = this.connectionFactory.createConnection(accessGrant);
UserProfile user = connection.fetchUserProfile();
return extractAuthentication(user);
}