List of usage examples for org.springframework.security.oauth2.common.exceptions InvalidGrantException InvalidGrantException
public InvalidGrantException(String msg)
From source file:org.cloudfoundry.identity.uaa.oauth.token.Saml2TokenGranter.java
@SuppressWarnings("unchecked") protected Authentication validateRequest(TokenRequest request) { // things to validate if (request == null || request.getRequestParameters() == null) { throw new InvalidGrantException("Missing token request object"); }/*from ww w . java2s.com*/ if (request.getRequestParameters().get("grant_type") == null) { throw new InvalidGrantException("Missing grant type"); } if (!GRANT_TYPE_SAML2_BEARER.equals(request.getRequestParameters().get("grant_type"))) { throw new InvalidGrantException("Invalid grant type"); } // parse the XML to Assertion if (new DefaultSecurityContextAccessor().isUser()) { return SecurityContextHolder.getContext().getAuthentication(); } throw new InvalidGrantException("User authentication not found"); }
From source file:org.cloudfoundry.identity.uaa.oauth.token.UaaTokenServices.java
@Override public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest request) throws AuthenticationException { if (null == refreshTokenValue) { throw new InvalidTokenException("Invalid refresh token (empty token)"); }/*from ww w . j a va2 s .c om*/ if (!"refresh_token".equals(request.getRequestParameters().get("grant_type"))) { throw new InvalidGrantException( "Invalid grant type: " + request.getRequestParameters().get("grant_type")); } Map<String, Object> claims = getClaimsForToken(refreshTokenValue); // TODO: Should reuse the access token you get after the first // successful authentication. // You will get an invalid_grant error if your previous token has not // expired yet. // OAuth2RefreshToken refreshToken = // tokenStore.readRefreshToken(refreshTokenValue); // if (refreshToken == null) { // throw new InvalidGrantException("Invalid refresh token: " + // refreshTokenValue); // } String clientId = (String) claims.get(CID); if (clientId == null || !clientId.equals(request.getClientId())) { throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue); } String userid = (String) claims.get(USER_ID); // TODO: Need to add a lookup by id so that the refresh token does not // need to contain a name UaaUser user = userDatabase.retrieveUserById(userid); Integer refreshTokenIssuedAt = (Integer) claims.get(IAT); long refreshTokenIssueDate = refreshTokenIssuedAt.longValue() * 1000l; // If the user changed their password, expire the refresh token if (user.getModified().after(new Date(refreshTokenIssueDate))) { logger.debug("User was last modified at " + user.getModified() + " refresh token was issued at " + new Date(refreshTokenIssueDate)); throw new InvalidTokenException("Invalid refresh token (password changed): " + refreshTokenValue); } Integer refreshTokenExpiry = (Integer) claims.get(EXP); long refreshTokenExpireDate = refreshTokenExpiry.longValue() * 1000l; if (new Date(refreshTokenExpireDate).before(new Date())) { throw new InvalidTokenException("Invalid refresh token (expired): " + refreshTokenValue + " expired at " + new Date(refreshTokenExpireDate)); } @SuppressWarnings("unchecked") ArrayList<String> tokenScopes = (ArrayList<String>) claims.get(SCOPE); // default request scopes to what is in the refresh token Set<String> requestedScopes = request.getScope(); if (requestedScopes.isEmpty()) { requestedScopes = new HashSet<String>(tokenScopes); } // The user may not request scopes that were not part of the refresh // token if (tokenScopes.isEmpty() || !tokenScopes.containsAll(requestedScopes)) { throw new InvalidScopeException( "Unable to narrow the scope of the client authentication to " + requestedScopes + ".", new HashSet<String>(tokenScopes)); } // from this point on, we only care about the scopes requested, not what // is in the refresh token // ensure all requested scopes are approved: either automatically or // explicitly by the user ClientDetails client = clientDetailsService.loadClientByClientId(clientId); String grantType = claims.get(GRANT_TYPE).toString(); checkForApproval(userid, clientId, requestedScopes, getAutoApprovedScopes(grantType, tokenScopes, client), new Date(refreshTokenIssueDate)); // if we have reached so far, issue an access token Integer validity = client.getAccessTokenValiditySeconds(); @SuppressWarnings("unchecked") Map<String, String> additionalAuthorizationInfo = (Map<String, String>) claims.get(ADDITIONAL_AZ_ATTR); Set<String> audience = new HashSet<>((ArrayList<String>) claims.get(AUD)); OAuth2AccessToken accessToken = createAccessToken(user.getId(), user.getUsername(), user.getEmail(), validity != null ? validity.intValue() : accessTokenValiditySeconds, null, requestedScopes, clientId, audience /*request.createOAuth2Request(client).getResourceIds()*/, grantType, refreshTokenValue, additionalAuthorizationInfo, new HashSet<String>()); //TODO populate response types return accessToken; }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServices.java
@Override public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest request) throws AuthenticationException { if (null == refreshTokenValue) { throw new InvalidTokenException("Invalid refresh token (empty token)"); }/*w w w. ja v a2 s . c om*/ if (!"refresh_token".equals(request.getRequestParameters().get("grant_type"))) { throw new InvalidGrantException( "Invalid grant type: " + request.getRequestParameters().get("grant_type")); } TokenValidation tokenValidation = validateToken(refreshTokenValue); Map<String, Object> claims = tokenValidation.getClaims(); refreshTokenValue = tokenValidation.getJwt().getEncoded(); @SuppressWarnings("unchecked") ArrayList<String> tokenScopes = (ArrayList<String>) claims.get(SCOPE); if (isRestrictRefreshGrant() && !tokenScopes.contains(UAA_REFRESH_TOKEN)) { throw new InsufficientScopeException(String.format("Expected scope %s is missing", UAA_REFRESH_TOKEN)); } // TODO: Should reuse the access token you get after the first // successful authentication. // You will get an invalid_grant error if your previous token has not // expired yet. // OAuth2RefreshToken refreshToken = // tokenStore.readRefreshToken(refreshTokenValue); // if (refreshToken == null) { // throw new InvalidGrantException("Invalid refresh token: " + // refreshTokenValue); // } String clientId = (String) claims.get(CID); if (clientId == null || !clientId.equals(request.getClientId())) { throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue); } String userid = (String) claims.get(USER_ID); String refreshTokenId = (String) claims.get(JTI); String accessTokenId = generateUniqueTokenId(); boolean opaque = TokenConstants.OPAQUE .equals(request.getRequestParameters().get(TokenConstants.REQUEST_TOKEN_FORMAT)); boolean revocable = opaque || (claims.get(REVOCABLE) == null ? false : (Boolean) claims.get(REVOCABLE)); // TODO: Need to add a lookup by id so that the refresh token does not // need to contain a name UaaUser user = userDatabase.retrieveUserById(userid); ClientDetails client = clientDetailsService.loadClientByClientId(clientId); Integer refreshTokenIssuedAt = (Integer) claims.get(IAT); long refreshTokenIssueDate = refreshTokenIssuedAt.longValue() * 1000l; Integer refreshTokenExpiry = (Integer) claims.get(EXP); long refreshTokenExpireDate = refreshTokenExpiry.longValue() * 1000l; if (new Date(refreshTokenExpireDate).before(new Date())) { throw new InvalidTokenException("Invalid refresh token (expired): " + refreshTokenValue + " expired at " + new Date(refreshTokenExpireDate)); } // default request scopes to what is in the refresh token Set<String> requestedScopes = request.getScope(); if (requestedScopes.isEmpty()) { requestedScopes = new HashSet<>(tokenScopes); } // The user may not request scopes that were not part of the refresh // token if (tokenScopes.isEmpty() || !tokenScopes.containsAll(requestedScopes)) { throw new InvalidScopeException( "Unable to narrow the scope of the client authentication to " + requestedScopes + ".", new HashSet<>(tokenScopes)); } // from this point on, we only care about the scopes requested, not what // is in the refresh token // ensure all requested scopes are approved: either automatically or // explicitly by the user String grantType = claims.get(GRANT_TYPE).toString(); checkForApproval(userid, clientId, requestedScopes, getAutoApprovedScopes(grantType, tokenScopes, client)); // if we have reached so far, issue an access token Integer validity = client.getAccessTokenValiditySeconds(); String nonce = (String) claims.get(NONCE); @SuppressWarnings("unchecked") Map<String, String> additionalAuthorizationInfo = (Map<String, String>) claims.get(ADDITIONAL_AZ_ATTR); @SuppressWarnings("unchecked") Map<String, String> externalAttributes = (Map<String, String>) claims.get(EXTERNAL_ATTR); String revocableHashSignature = (String) claims.get(REVOCATION_SIGNATURE); if (hasText(revocableHashSignature)) { String clientSecretForHash = client.getClientSecret(); if (clientSecretForHash != null && clientSecretForHash.split(" ").length > 1) { clientSecretForHash = clientSecretForHash.split(" ")[1]; } String newRevocableHashSignature = UaaTokenUtils.getRevocableTokenSignature(client, clientSecretForHash, user); if (!revocableHashSignature.equals(newRevocableHashSignature)) { throw new TokenRevokedException(refreshTokenValue); } } Set<String> audience = new HashSet<>((ArrayList<String>) claims.get(AUD)); int zoneAccessTokenValidity = getZoneAccessTokenValidity(); CompositeAccessToken accessToken = createAccessToken(accessTokenId, user.getId(), user, (claims.get(AUTH_TIME) != null) ? new Date(((Long) claims.get(AUTH_TIME)) * 1000l) : null, validity != null ? validity.intValue() : zoneAccessTokenValidity, null, requestedScopes, clientId, audience /*request.createOAuth2Request(client).getResourceIds()*/, grantType, refreshTokenValue, nonce, additionalAuthorizationInfo, externalAttributes, new HashSet<>(), revocableHashSignature, false, null, //TODO populate response types null, revocable, null, null); DefaultExpiringOAuth2RefreshToken expiringRefreshToken = new DefaultExpiringOAuth2RefreshToken( refreshTokenValue, new Date(refreshTokenExpireDate)); return persistRevocableToken(accessTokenId, refreshTokenId, accessToken, expiringRefreshToken, clientId, user.getId(), opaque, revocable); }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenStore.java
@Override public OAuth2Authentication consumeAuthorizationCode(String code) throws InvalidGrantException { performExpirationClean();// w ww . ja va 2s .c om JdbcTemplate template = new JdbcTemplate(dataSource); try { TokenCode tokenCode = (TokenCode) template.queryForObject(SQL_SELECT_STATEMENT, rowMapper, code); if (tokenCode != null) { try { if (tokenCode.isExpired()) { logger.debug("[oauth_code] Found code, but it expired:" + tokenCode); throw new InvalidGrantException("Authorization code expired: " + code); } else if (tokenCode.getExpiresAt() == 0) { return SerializationUtils.deserialize(tokenCode.getAuthentication()); } else { return deserializeOauth2Authentication(tokenCode.getAuthentication()); } } finally { template.update(SQL_DELETE_STATEMENT, code); } } } catch (EmptyResultDataAccessException x) { } throw new InvalidGrantException("Invalid authorization code: " + code); }
From source file:org.orcid.core.oauth.OrcidClientCredentialsChecker.java
private void validateGrantType(String grantType, ClientDetails clientDetails) { Collection<String> authorizedGrantTypes = clientDetails.getAuthorizedGrantTypes(); if (authorizedGrantTypes != null && !authorizedGrantTypes.isEmpty() && !authorizedGrantTypes.contains(grantType)) { throw new InvalidGrantException("Unauthorized grant type: " + grantType); }//from w w w . ja v a 2 s . c o m }
From source file:org.springframework.security.oauth2.provider.token.AbstractTokenGranter.java
protected void validateGrantType(String grantType, ClientDetails clientDetails) { Collection<String> authorizedGrantTypes = clientDetails.getAuthorizedGrantTypes(); if (authorizedGrantTypes != null && !authorizedGrantTypes.isEmpty() && !authorizedGrantTypes.contains(grantType)) { throw new InvalidGrantException("Unauthorized grant type: " + grantType); }//from w w w. j ava2s . co m }