List of usage examples for org.springframework.security.oauth2.common.exceptions InvalidTokenException InvalidTokenException
public InvalidTokenException(String msg)
From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateRemoteTokenServices.java
/** * {@inheritDoc}/*from w w w. j ava 2 s . c o m*/ */ @Override public OAuth2Authentication loadAuthentication(final String accessToken) throws AuthenticationException, InvalidTokenException { final long start = System.nanoTime(); try { final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add(TOKEN_NAME_KEY, accessToken); formData.add(CLIENT_ID_KEY, this.clientId); formData.add(CLIENT_SECRET_KEY, this.clientSecret); formData.add(GRANT_TYPE_KEY, GRANT_TYPE); final Map<String, Object> map = this.postForMap(this.checkTokenEndpointUrl, formData); if (map.containsKey(ERROR_KEY)) { final String error = map.get(ERROR_KEY).toString(); log.debug("Validating the token produced an error: {}", error); throw new InvalidTokenException(error); } Assert.state(map.containsKey(CLIENT_ID_KEY), "Client id must be present in response from auth server"); Assert.state(map.containsKey(SCOPE_KEY), "No scopes included in response from authentication server"); this.convertScopes(map); final OAuth2Authentication authentication = this.converter.extractAuthentication(map); log.info("User {} authenticated with authorities {}", authentication.getPrincipal(), authentication.getAuthorities()); return authentication; } finally { final long finished = System.nanoTime(); this.authenticationTimer.record(finished - start, TimeUnit.NANOSECONDS); } }
From source file:com.ge.predix.uaa.token.lib.FastTokenServices.java
private void verifyIssuer(final String iss) { if ((null != this.trustedIssuers) && (0 < this.trustedIssuers.size())) { if (!this.trustedIssuers.contains(iss)) { throw new InvalidTokenException("The issuer '" + iss + "' is not trusted " + "because it is not in the configured list of trusted issuers: " + this.trustedIssuers + "."); }//from ww w . ja va 2 s. c om return; } }
From source file:com.ge.predix.uaa.token.lib.FastTokenServices.java
private void verifyTimeWindow(final Map<String, Object> claims) { Date iatDate = getIatDate(claims); Date expDate = getExpDate(claims); Date currentDate = new Date(); if (iatDate != null && iatDate.after(currentDate)) { throw new InvalidTokenException(String.format( "Token validity window is in the future. Token is issued at [%s]. Current date is [%s]", iatDate.toString(), currentDate.toString())); }//from w w w. j a v a 2 s . com if (expDate != null && expDate.before(currentDate)) { throw new InvalidTokenException( String.format("Token is expired. Expiration date is [%s]. Current date is [%s]", expDate.toString(), currentDate.toString())); } }
From source file:com.ge.predix.uaa.token.lib.TestTokenUtil.java
private DefaultOAuth2AccessToken createAccessToken(final String issuerId, final String userId, final String username, final String userEmail, final int validitySeconds, final Collection<GrantedAuthority> clientScopes, final Set<String> requestedScopes, final String clientId, final Set<String> resourceIds, final String grantType, final String refreshToken, final Map<String, String> additionalAuthorizationAttributes, final Set<String> responseTypes, final String revocableHashSignature, final long issuedAtMillis, final String zoneId) { String tokenId = UUID.randomUUID().toString(); DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(tokenId); if (validitySeconds > 0) { accessToken.setExpiration(new Date(issuedAtMillis + (validitySeconds * 1000L))); }/*from ww w . jav a2 s. com*/ accessToken.setRefreshToken(refreshToken == null ? null : new DefaultOAuth2RefreshToken(refreshToken)); if (null == requestedScopes || requestedScopes.size() == 0) { // logger.debug("No scopes were granted"); throw new InvalidTokenException("No scopes were granted"); } accessToken.setScope(requestedScopes); Map<String, Object> info = new HashMap<String, Object>(); info.put(JTI, accessToken.getValue()); if (null != additionalAuthorizationAttributes) { info.put(ADDITIONAL_AZ_ATTR, additionalAuthorizationAttributes); } accessToken.setAdditionalInformation(info); String content; try { content = JsonUtils.writeValueAsString(createJWTAccessToken(accessToken, issuerId, userId, username, userEmail, clientScopes, requestedScopes, clientId, resourceIds, grantType, refreshToken, revocableHashSignature, issuedAtMillis, zoneId)); } catch (JsonUtils.JsonUtilException e) { throw new IllegalStateException("Cannot convert access token to JSON", e); } String token = JwtHelper.encode(content, this.signer).getEncoded(); // This setter copies the value and returns. Don't change. accessToken.setValue(token); return accessToken; }
From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateRemoteTokenServices.java
private void convertScopes(final Map<String, Object> oauth2Map) { final Object scopesObject = oauth2Map.get(SCOPE_KEY); if (scopesObject == null) { throw new InvalidTokenException("Scopes were null"); }/*from w w w . j a v a 2s .c o m*/ if (scopesObject instanceof String) { final String scopes = (String) scopesObject; if (StringUtils.isBlank(scopes)) { throw new InvalidTokenException("No scopes found unable to authenticate"); } oauth2Map.put(SCOPE_KEY, Arrays.asList(StringUtils.split(scopes, ' '))); } else { throw new InvalidTokenException("Scopes was not a String"); } }
From source file:org.mitre.oauth2.service.impl.DefaultOAuth2ProviderTokenService.java
@Override public OAuth2AccessTokenEntity refreshAccessToken(String refreshTokenValue, TokenRequest authRequest) throws AuthenticationException { OAuth2RefreshTokenEntity refreshToken = clearExpiredRefreshToken( tokenRepository.getRefreshTokenByValue(refreshTokenValue)); if (refreshToken == null) { throw new InvalidTokenException("Invalid refresh token: " + refreshTokenValue); }//from www. jav a 2s. co m ClientDetailsEntity client = refreshToken.getClient(); AuthenticationHolderEntity authHolder = refreshToken.getAuthenticationHolder(); // make sure that the client requesting the token is the one who owns the refresh token ClientDetailsEntity requestingClient = clientDetailsService.loadClientByClientId(authRequest.getClientId()); if (!client.getClientId().equals(requestingClient.getClientId())) { tokenRepository.removeRefreshToken(refreshToken); throw new InvalidClientException("Client does not own the presented refresh token"); } //Make sure this client allows access token refreshing if (!client.isAllowRefresh()) { throw new InvalidClientException("Client does not allow refreshing access token!"); } // clear out any access tokens if (client.isClearAccessTokensOnRefresh()) { tokenRepository.clearAccessTokensForRefreshToken(refreshToken); } if (refreshToken.isExpired()) { tokenRepository.removeRefreshToken(refreshToken); throw new InvalidTokenException("Expired refresh token: " + refreshTokenValue); } OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity(); // get the stored scopes from the authentication holder's authorization request; these are the scopes associated with the refresh token Set<String> refreshScopesRequested = new HashSet<>( refreshToken.getAuthenticationHolder().getAuthentication().getOAuth2Request().getScope()); Set<SystemScope> refreshScopes = scopeService.fromStrings(refreshScopesRequested); // remove any of the special system scopes refreshScopes = scopeService.removeReservedScopes(refreshScopes); Set<String> scopeRequested = authRequest.getScope() == null ? new HashSet<String>() : new HashSet<>(authRequest.getScope()); Set<SystemScope> scope = scopeService.fromStrings(scopeRequested); // remove any of the special system scopes scope = scopeService.removeReservedScopes(scope); if (scope != null && !scope.isEmpty()) { // ensure a proper subset of scopes if (refreshScopes != null && refreshScopes.containsAll(scope)) { // set the scope of the new access token if requested token.setScope(scopeService.toStrings(scope)); } else { String errorMsg = "Up-scoping is not allowed."; logger.error(errorMsg); throw new InvalidScopeException(errorMsg); } } else { // otherwise inherit the scope of the refresh token (if it's there -- this can return a null scope set) token.setScope(scopeService.toStrings(refreshScopes)); } token.setClient(client); if (client.getAccessTokenValiditySeconds() != null) { Date expiration = new Date( System.currentTimeMillis() + (client.getAccessTokenValiditySeconds() * 1000L)); token.setExpiration(expiration); } if (client.isReuseRefreshToken()) { // if the client re-uses refresh tokens, do that token.setRefreshToken(refreshToken); } else { // otherwise, make a new refresh token OAuth2RefreshTokenEntity newRefresh = createRefreshToken(client, authHolder); token.setRefreshToken(newRefresh); // clean up the old refresh token tokenRepository.removeRefreshToken(refreshToken); } token.setAuthenticationHolder(authHolder); tokenEnhancer.enhance(token, authHolder.getAuthentication()); tokenRepository.saveAccessToken(token); return token; }
From source file:org.mitre.oauth2.service.impl.DefaultOAuth2ProviderTokenService.java
@Override public OAuth2Authentication loadAuthentication(String accessTokenValue) throws AuthenticationException { OAuth2AccessTokenEntity accessToken = clearExpiredAccessToken( tokenRepository.getAccessTokenByValue(accessTokenValue)); if (accessToken == null) { throw new InvalidTokenException("Invalid access token: " + accessTokenValue); } else {/*ww w .j a v a 2s. co m*/ return accessToken.getAuthenticationHolder().getAuthentication(); } }
From source file:org.mitre.oauth2.service.impl.DefaultOAuth2ProviderTokenService.java
/** * Get an access token from its token value. *///from ww w .j a v a 2s.c o m @Override public OAuth2AccessTokenEntity readAccessToken(String accessTokenValue) throws AuthenticationException { OAuth2AccessTokenEntity accessToken = clearExpiredAccessToken( tokenRepository.getAccessTokenByValue(accessTokenValue)); if (accessToken == null) { throw new InvalidTokenException("Access token for value " + accessTokenValue + " was not found"); } else { return accessToken; } }
From source file:org.mitre.oauth2.service.impl.DefaultOAuth2ProviderTokenService.java
/** * Get a refresh token by its token value. *//* w w w .j a v a2 s . c o m*/ @Override public OAuth2RefreshTokenEntity getRefreshToken(String refreshTokenValue) throws AuthenticationException { OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenByValue(refreshTokenValue); if (refreshToken == null) { throw new InvalidTokenException("Refresh token for value " + refreshTokenValue + " was not found"); } else { return refreshToken; } }