List of usage examples for org.apache.commons.codec.digest DigestUtils sha256Hex
public static String sha256Hex(String data)
From source file:org.wso2.carbon.identity.oauth2.authz.handlers.util.ResponseTypeHandlerUtil.java
private static boolean isRefreshTokenValid(AccessTokenDO tokenBean) { if (tokenBean != null) { long refreshTokenExpireTime = OAuth2Util.getRefreshTokenExpireTimeMillis(tokenBean); if (TOKEN_STATE_ACTIVE.equals(tokenBean.getTokenState())) { String consumerKey = tokenBean.getConsumerKey(); if (!isRefreshTokenExpired(tokenBean.getConsumerKey(), refreshTokenExpireTime)) { if (log.isDebugEnabled()) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Existing access token(hashed): " + DigestUtils.sha256Hex(tokenBean.getAccessToken()) + " has expired, but refresh token(hashed):" + DigestUtils.sha256Hex(tokenBean.getRefreshToken()) + " is still valid for client: " + consumerKey + ". Remaining time: " + refreshTokenExpireTime + " ms. Using " + "existing refresh token."); } else { log.debug("Existing access token has expired, but refresh token is still valid for " + "client: " + consumerKey + ". Remaining time: " + refreshTokenExpireTime + "ms. " + "Using existing refresh token."); }/*w ww . j ava2 s . c o m*/ } return true; } else { // no valid refresh token found in existing Token if (log.isDebugEnabled()) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.REFRESH_TOKEN)) { log.debug("Refresh token: " + tokenBean.getRefreshToken() + " for client: " + tokenBean.getConsumerKey() + " is expired. Issuing a new refresh token."); } else { log.debug("Refresh token for client: " + tokenBean.getConsumerKey() + " is expired. " + "Issuing a new refresh token."); } } } } } return false; }
From source file:org.wso2.carbon.identity.oauth2.authz.handlers.util.ResponseTypeHandlerUtil.java
private static void removeTokenFromCache(OAuthCacheKey cacheKey, AccessTokenDO tokenBean) { OAuthCache.getInstance().clearCacheEntry(cacheKey); if (log.isDebugEnabled()) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Access token(hashed): " + DigestUtils.sha256Hex(tokenBean.getAccessToken()) + " is expired" + ". Therefore cleared it from cache."); } else {/*ww w.jav a 2s .c o m*/ log.debug("Existing access token for client: " + tokenBean.getConsumerKey() + " is expired. " + "Therefore cleared it from cache."); } } }
From source file:org.wso2.carbon.identity.oauth2.dao.AccessTokenDAOImpl.java
private void insertAccessToken(String accessToken, String consumerKey, AccessTokenDO accessTokenDO, Connection connection, String userStoreDomain, int retryAttemptCounter) throws IdentityOAuth2Exception { if (!isPersistenceEnabled()) { return;/* w ww. j a v a 2 s .co m*/ } if (accessTokenDO == null) { throw new IdentityOAuth2Exception( "Access token data object should be available for further execution."); } if (accessTokenDO.getAuthzUser() == null) { throw new IdentityOAuth2Exception("Authorized user should be available for further execution."); } try { OauthTokenIssuer oauthTokenIssuer = OAuth2Util.getOAuthTokenIssuerForOAuthApp(consumerKey); //check for persist alias for the token type if (oauthTokenIssuer.usePersistedAccessTokenAlias()) { accessToken = oauthTokenIssuer.getAccessTokenHash(accessToken); } } catch (OAuthSystemException e) { if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Error while getting access token hash for token(hashed): " + DigestUtils.sha256Hex(accessToken)); } throw new IdentityOAuth2Exception("Error while getting access token hash."); } catch (InvalidOAuthClientException e) { throw new IdentityOAuth2Exception( "Error while retrieving oauth issuer for the app with clientId: " + consumerKey, e); } if (log.isDebugEnabled()) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Persisting access token(hashed): " + DigestUtils.sha256Hex(accessToken) + " for client: " + consumerKey + " user: " + accessTokenDO.getAuthzUser().toString() + " scope: " + Arrays.toString(accessTokenDO.getScope())); } else { log.debug("Persisting access token for client: " + consumerKey + " user: " + accessTokenDO.getAuthzUser().toString() + " scope: " + Arrays.toString(accessTokenDO.getScope())); } } userStoreDomain = OAuth2Util.getSanitizedUserStoreDomain(userStoreDomain); String userDomain = accessTokenDO.getAuthzUser().getUserStoreDomain(); String authenticatedIDP = accessTokenDO.getAuthzUser().getFederatedIdPName(); PreparedStatement insertTokenPrepStmt = null; PreparedStatement addScopePrepStmt = null; if (!OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal() && accessTokenDO.getAuthzUser().isFederatedUser()) { if (log.isDebugEnabled()) { log.debug("Adding federated domain to user store domain to user " + accessTokenDO.getAuthzUser().getAuthenticatedSubjectIdentifier()); } userDomain = OAuth2Util.getFederatedUserDomain(authenticatedIDP); } if (log.isDebugEnabled()) { log.debug("Userstore domain for user " + accessTokenDO.getAuthzUser().getAuthenticatedSubjectIdentifier() + " is :" + userDomain); } String sql = OAuth2Util.getTokenPartitionedSqlByUserStore(SQLQueries.INSERT_OAUTH2_ACCESS_TOKEN, userDomain); String sqlAddScopes = OAuth2Util.getTokenPartitionedSqlByUserStore(SQLQueries.INSERT_OAUTH2_TOKEN_SCOPE, userDomain); try { insertTokenPrepStmt = connection.prepareStatement(sql); insertTokenPrepStmt.setString(1, getPersistenceProcessor().getProcessedAccessTokenIdentifier(accessToken)); if (accessTokenDO.getRefreshToken() != null) { insertTokenPrepStmt.setString(2, getPersistenceProcessor().getProcessedRefreshToken(accessTokenDO.getRefreshToken())); } else { insertTokenPrepStmt.setString(2, accessTokenDO.getRefreshToken()); } insertTokenPrepStmt.setString(3, accessTokenDO.getAuthzUser().getUserName()); int tenantId = OAuth2Util.getTenantId(accessTokenDO.getAuthzUser().getTenantDomain()); insertTokenPrepStmt.setInt(4, tenantId); insertTokenPrepStmt.setString(5, OAuth2Util.getSanitizedUserStoreDomain(userDomain)); insertTokenPrepStmt.setTimestamp(6, accessTokenDO.getIssuedTime(), Calendar.getInstance(TimeZone.getTimeZone(UTC))); insertTokenPrepStmt.setTimestamp(7, accessTokenDO.getRefreshTokenIssuedTime(), Calendar.getInstance(TimeZone.getTimeZone(UTC))); insertTokenPrepStmt.setLong(8, accessTokenDO.getValidityPeriodInMillis()); insertTokenPrepStmt.setLong(9, accessTokenDO.getRefreshTokenValidityPeriodInMillis()); insertTokenPrepStmt.setString(10, OAuth2Util.hashScopes(accessTokenDO.getScope())); insertTokenPrepStmt.setString(11, accessTokenDO.getTokenState()); insertTokenPrepStmt.setString(12, accessTokenDO.getTokenType()); insertTokenPrepStmt.setString(13, accessTokenDO.getTokenId()); insertTokenPrepStmt.setString(14, accessTokenDO.getGrantType()); insertTokenPrepStmt.setString(15, accessTokenDO.getAuthzUser().getAuthenticatedSubjectIdentifier()); insertTokenPrepStmt.setString(16, getHashingPersistenceProcessor().getProcessedAccessTokenIdentifier(accessToken)); if (accessTokenDO.getRefreshToken() != null) { insertTokenPrepStmt.setString(17, getHashingPersistenceProcessor().getProcessedRefreshToken(accessTokenDO.getRefreshToken())); } else { insertTokenPrepStmt.setString(17, accessTokenDO.getRefreshToken()); } insertTokenPrepStmt.setString(18, getPersistenceProcessor().getProcessedClientId(consumerKey)); insertTokenPrepStmt.execute(); String accessTokenId = accessTokenDO.getTokenId(); addScopePrepStmt = connection.prepareStatement(sqlAddScopes); if (accessTokenDO.getScope() != null && accessTokenDO.getScope().length > 0) { for (String scope : accessTokenDO.getScope()) { addScopePrepStmt.setString(1, accessTokenId); addScopePrepStmt.setString(2, scope); addScopePrepStmt.setInt(3, tenantId); addScopePrepStmt.execute(); } } if (retryAttemptCounter > 0) { log.info("Successfully recovered 'CON_APP_KEY' constraint violation with the attempt : " + retryAttemptCounter); } } catch (SQLIntegrityConstraintViolationException e) { IdentityDatabaseUtil.rollBack(connection); if (retryAttemptCounter >= getTokenPersistRetryCount()) { log.error("'CON_APP_KEY' constrain violation retry count exceeds above the maximum count - " + getTokenPersistRetryCount()); String errorMsg = "Access Token for consumer key : " + consumerKey + ", user : " + accessTokenDO.getAuthzUser() + " and scope : " + OAuth2Util.buildScopeString(accessTokenDO.getScope()) + "already exists"; throw new IdentityOAuth2Exception(errorMsg, e); } recoverFromConAppKeyConstraintViolation(accessToken, consumerKey, accessTokenDO, connection, userStoreDomain, retryAttemptCounter + 1); } catch (DataTruncation e) { IdentityDatabaseUtil.rollBack(connection); throw new IdentityOAuth2Exception("Invalid request", e); } catch (SQLException e) { IdentityDatabaseUtil.rollBack(connection); // Handle constrain violation issue in JDBC drivers which does not throw // SQLIntegrityConstraintViolationException if (StringUtils.containsIgnoreCase(e.getMessage(), "CON_APP_KEY")) { if (retryAttemptCounter >= getTokenPersistRetryCount()) { log.error("'CON_APP_KEY' constrain violation retry count exceeds above the maximum count - " + getTokenPersistRetryCount()); String errorMsg = "Access Token for consumer key : " + consumerKey + ", user : " + accessTokenDO.getAuthzUser() + " and scope : " + OAuth2Util.buildScopeString(accessTokenDO.getScope()) + "already exists"; throw new IdentityOAuth2Exception(errorMsg, e); } recoverFromConAppKeyConstraintViolation(accessToken, consumerKey, accessTokenDO, connection, userStoreDomain, retryAttemptCounter + 1); } else { throw new IdentityOAuth2Exception( "Error when storing the access token for consumer key : " + consumerKey, e); } } finally { IdentityDatabaseUtil.closeStatement(addScopePrepStmt); IdentityDatabaseUtil.closeStatement(insertTokenPrepStmt); } }
From source file:org.wso2.carbon.identity.oauth2.dao.AccessTokenDAOImpl.java
@Override public boolean insertAccessToken(String accessToken, String consumerKey, AccessTokenDO newAccessTokenDO, AccessTokenDO existingAccessTokenDO, String rawUserStoreDomain) throws IdentityOAuth2Exception { if (!isPersistenceEnabled()) { return false; }//from w w w . j ava 2 s .c o m if (log.isDebugEnabled()) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Persisting access token(hashed): " + DigestUtils.sha256Hex(accessToken) + " for client: " + consumerKey + " user: " + newAccessTokenDO.getAuthzUser().toString() + " scope: " + Arrays.toString(newAccessTokenDO.getScope())); } else { log.debug("Persisting access token for client: " + consumerKey + " user: " + newAccessTokenDO.getAuthzUser().toString() + " scope: " + Arrays.toString(newAccessTokenDO.getScope())); } } String userStoreDomain = OAuth2Util.getSanitizedUserStoreDomain(rawUserStoreDomain); Connection connection = IdentityDatabaseUtil.getDBConnection(); try { connection.setAutoCommit(false); if (existingAccessTokenDO != null) { // Mark the existing access token as expired on database if a token exist for the user updateAccessTokenState(connection, existingAccessTokenDO.getTokenId(), OAuthConstants.TokenStates.TOKEN_STATE_EXPIRED, UUID.randomUUID().toString(), userStoreDomain); } insertAccessToken(accessToken, consumerKey, newAccessTokenDO, connection, userStoreDomain); if (isTokenCleanupFeatureEnabled && existingAccessTokenDO != null) { oldTokenCleanupObject.cleanupTokenByTokenId(existingAccessTokenDO.getTokenId(), connection); } connection.commit(); return true; } catch (SQLException e) { throw new IdentityOAuth2Exception("Error occurred while persisting access token", e); } finally { IdentityDatabaseUtil.closeConnection(connection); } }
From source file:org.wso2.carbon.identity.oauth2.dao.AccessTokenDAOImpl.java
@Override public AccessTokenDO getLatestAccessToken(String consumerKey, AuthenticatedUser authzUser, String userStoreDomain, String scope, boolean includeExpiredTokens) throws IdentityOAuth2Exception { if (log.isDebugEnabled()) { log.debug("Retrieving latest access token for client: " + consumerKey + " user: " + authzUser.toString() + " scope: " + scope); }//from ww w. j av a 2 s. c om boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(authzUser.toString()); String tenantDomain = authzUser.getTenantDomain(); int tenantId = OAuth2Util.getTenantId(tenantDomain); String tenantAwareUsernameWithNoUserDomain = authzUser.getUserName(); String userDomain; if (!OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal() && authzUser.isFederatedUser()) { if (log.isDebugEnabled()) { log.debug( "User is federated and not mapped to local users. Hence adding federated domain as domain"); } userDomain = OAuth2Util.getFederatedUserDomain(authzUser.getFederatedIdPName()); } else { userDomain = OAuth2Util.getSanitizedUserStoreDomain(authzUser.getUserStoreDomain()); } if (log.isDebugEnabled()) { log.debug("User domain is set to :" + userDomain); } Connection connection = IdentityDatabaseUtil.getDBConnection(); PreparedStatement prepStmt = null; ResultSet resultSet = null; try { String sql; if (connection.getMetaData().getDriverName().contains("MySQL") || connection.getMetaData().getDriverName().contains("H2")) { sql = SQLQueries.RETRIEVE_LATEST_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_MYSQL; } else if (connection.getMetaData().getDatabaseProductName().contains("DB2")) { sql = SQLQueries.RETRIEVE_LATEST_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_DB2SQL; } else if (connection.getMetaData().getDriverName().contains("MS SQL")) { sql = SQLQueries.RETRIEVE_LATEST_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_MSSQL; } else if (connection.getMetaData().getDriverName().contains("Microsoft")) { sql = SQLQueries.RETRIEVE_LATEST_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_MSSQL; } else if (connection.getMetaData().getDriverName().contains("PostgreSQL")) { sql = SQLQueries.RETRIEVE_LATEST_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_POSTGRESQL; } else if (connection.getMetaData().getDriverName().contains("Informix")) { // Driver name = "IBM Informix JDBC Driver for IBM Informix Dynamic Server" sql = SQLQueries.RETRIEVE_LATEST_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_INFORMIX; } else { sql = SQLQueries.RETRIEVE_LATEST_ACCESS_TOKEN_BY_CLIENT_ID_USER_SCOPE_ORACLE; } if (!includeExpiredTokens) { sql = sql.replace("TOKEN_SCOPE_HASH=?", "TOKEN_SCOPE_HASH=? AND TOKEN_STATE='ACTIVE'"); } sql = OAuth2Util.getTokenPartitionedSqlByUserStore(sql, userDomain); if (!isUsernameCaseSensitive) { sql = sql.replace(AUTHZ_USER, LOWER_AUTHZ_USER); } String hashedScope = OAuth2Util.hashScopes(scope); if (hashedScope == null) { sql = sql.replace("TOKEN_SCOPE_HASH=?", "TOKEN_SCOPE_HASH IS NULL"); } prepStmt = connection.prepareStatement(sql); prepStmt.setString(1, getPersistenceProcessor().getProcessedClientId(consumerKey)); if (isUsernameCaseSensitive) { prepStmt.setString(2, tenantAwareUsernameWithNoUserDomain); } else { prepStmt.setString(2, tenantAwareUsernameWithNoUserDomain.toLowerCase()); } prepStmt.setInt(3, tenantId); prepStmt.setString(4, userDomain); if (hashedScope != null) { prepStmt.setString(5, hashedScope); } resultSet = prepStmt.executeQuery(); if (resultSet.next()) { boolean returnToken = false; String tokenState = resultSet.getString(7); if (includeExpiredTokens) { if (OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE.equals(tokenState) || OAuthConstants.TokenStates.TOKEN_STATE_EXPIRED.equals(tokenState)) { returnToken = true; } } else { if (OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE.equals(tokenState)) { returnToken = true; } } if (returnToken) { String accessToken = null; if (isHashDisabled) { accessToken = getPersistenceProcessor() .getPreprocessedAccessTokenIdentifier(resultSet.getString(1)); } else { accessToken = resultSet.getString(1); } String refreshToken = null; if (resultSet.getString(2) != null) { if (isHashDisabled) { refreshToken = getPersistenceProcessor() .getPreprocessedRefreshToken(resultSet.getString(2)); } else { refreshToken = resultSet.getString(2); } } long issuedTime = resultSet.getTimestamp(3, Calendar.getInstance(TimeZone.getTimeZone(UTC))) .getTime(); long refreshTokenIssuedTime = resultSet .getTimestamp(4, Calendar.getInstance(TimeZone.getTimeZone(UTC))).getTime(); long validityPeriodInMillis = resultSet.getLong(5); long refreshTokenValidityPeriodInMillis = resultSet.getLong(6); String userType = resultSet.getString(8); String tokenId = resultSet.getString(9); String subjectIdentifier = resultSet.getString(10); // data loss at dividing the validity period but can be neglected AuthenticatedUser user = new AuthenticatedUser(); user.setUserName(tenantAwareUsernameWithNoUserDomain); user.setTenantDomain(tenantDomain); user.setUserStoreDomain(userDomain); ServiceProvider serviceProvider; try { serviceProvider = OAuth2ServiceComponentHolder.getApplicationMgtService() .getServiceProviderByClientId(consumerKey, OAuthConstants.Scope.OAUTH2, tenantDomain); } catch (IdentityApplicationManagementException e) { throw new IdentityOAuth2Exception( "Error occurred while retrieving OAuth2 application data for " + "client id " + consumerKey, e); } user.setAuthenticatedSubjectIdentifier(subjectIdentifier, serviceProvider); AccessTokenDO accessTokenDO = new AccessTokenDO(consumerKey, user, OAuth2Util.buildScopeArray(scope), new Timestamp(issuedTime), new Timestamp(refreshTokenIssuedTime), validityPeriodInMillis, refreshTokenValidityPeriodInMillis, userType); accessTokenDO.setAccessToken(accessToken); accessTokenDO.setRefreshToken(refreshToken); accessTokenDO.setTokenState(tokenState); accessTokenDO.setTokenId(tokenId); if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Retrieved latest access token(hashed): " + DigestUtils.sha256Hex(accessToken) + " for client: " + consumerKey + " user: " + authzUser.toString() + " scope: " + scope); } return accessTokenDO; } } return null; } catch (SQLException e) { String errorMsg = "Error occurred while trying to retrieve latest 'ACTIVE' " + "access token for Client ID : " + consumerKey + ", User ID : " + authzUser + " and Scope : " + scope; if (includeExpiredTokens) { errorMsg = errorMsg.replace("ACTIVE", "ACTIVE or EXPIRED"); } throw new IdentityOAuth2Exception(errorMsg, e); } finally { IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt); } }
From source file:org.wso2.carbon.identity.oauth2.dao.AccessTokenDAOImpl.java
@Override public AccessTokenDO getAccessToken(String accessTokenIdentifier, boolean includeExpired) throws IdentityOAuth2Exception { if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Retrieving information of access token(hashed): " + DigestUtils.sha256Hex(accessTokenIdentifier)); }//from w w w . j a v a 2 s. co m AccessTokenDO dataDO = null; Connection connection = IdentityDatabaseUtil.getDBConnection(); PreparedStatement prepStmt = null; ResultSet resultSet = null; try { String sql; if (includeExpired) { sql = SQLQueries.RETRIEVE_ACTIVE_EXPIRED_ACCESS_TOKEN; } else { sql = SQLQueries.RETRIEVE_ACTIVE_ACCESS_TOKEN; } sql = OAuth2Util.getTokenPartitionedSqlByToken(sql, accessTokenIdentifier); prepStmt = connection.prepareStatement(sql); prepStmt.setString(1, getHashingPersistenceProcessor().getProcessedAccessTokenIdentifier(accessTokenIdentifier)); resultSet = prepStmt.executeQuery(); int iterateId = 0; List<String> scopes = new ArrayList<>(); while (resultSet.next()) { if (iterateId == 0) { String consumerKey = getPersistenceProcessor().getPreprocessedClientId(resultSet.getString(1)); String authorizedUser = resultSet.getString(2); int tenantId = resultSet.getInt(3); String tenantDomain = OAuth2Util.getTenantDomain(tenantId); String userDomain = resultSet.getString(4); String[] scope = OAuth2Util.buildScopeArray(resultSet.getString(5)); Timestamp issuedTime = resultSet.getTimestamp(6, Calendar.getInstance(TimeZone.getTimeZone(UTC))); Timestamp refreshTokenIssuedTime = resultSet.getTimestamp(7, Calendar.getInstance(TimeZone.getTimeZone(UTC))); long validityPeriodInMillis = resultSet.getLong(8); long refreshTokenValidityPeriodMillis = resultSet.getLong(9); String tokenType = resultSet.getString(10); String refreshToken = resultSet.getString(11); String tokenId = resultSet.getString(12); String grantType = resultSet.getString(13); String subjectIdentifier = resultSet.getString(14); AuthenticatedUser user = new AuthenticatedUser(); user.setUserName(authorizedUser); user.setUserStoreDomain(userDomain); user.setTenantDomain(tenantDomain); ServiceProvider serviceProvider; try { serviceProvider = OAuth2ServiceComponentHolder.getApplicationMgtService() .getServiceProviderByClientId(consumerKey, OAuthConstants.Scope.OAUTH2, tenantDomain); } catch (IdentityApplicationManagementException e) { throw new IdentityOAuth2Exception( "Error occurred while retrieving OAuth2 application data for client id " + consumerKey, e); } user.setAuthenticatedSubjectIdentifier(subjectIdentifier, serviceProvider); if (!OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal() && userDomain.startsWith(OAuthConstants.UserType.FEDERATED_USER_DOMAIN_PREFIX)) { if (log.isDebugEnabled()) { log.debug( "Federated prefix found in domain " + userDomain + "and federated users are not" + " mapped to local users. Hence setting user to a federated user"); } user.setFederatedUser(true); } dataDO = new AccessTokenDO(consumerKey, user, scope, issuedTime, refreshTokenIssuedTime, validityPeriodInMillis, refreshTokenValidityPeriodMillis, tokenType); dataDO.setAccessToken(accessTokenIdentifier); dataDO.setRefreshToken(refreshToken); dataDO.setTokenId(tokenId); dataDO.setGrantType(grantType); dataDO.setTenantID(tenantId); } else { scopes.add(resultSet.getString(5)); } iterateId++; } if (scopes.size() > 0 && dataDO != null) { dataDO.setScope( (String[]) ArrayUtils.addAll(dataDO.getScope(), scopes.toArray(new String[scopes.size()]))); } } catch (SQLException e) { throw new IdentityOAuth2Exception("Error when retrieving Access Token" + e); } finally { IdentityDatabaseUtil.closeAllConnections(connection, resultSet, prepStmt); } return dataDO; }
From source file:org.wso2.carbon.identity.oauth2.dao.AccessTokenDAOImpl.java
@Override public void revokeAccessTokensInBatch(String[] tokens) throws IdentityOAuth2Exception { if (log.isDebugEnabled()) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { StringBuilder stringBuilder = new StringBuilder(); for (String token : tokens) { stringBuilder.append(DigestUtils.sha256Hex(token)).append(" "); }//from w ww . j a v a 2s . com log.debug("Revoking access tokens(hashed): " + stringBuilder.toString()); } else { log.debug("Revoking access tokens in batch mode"); } } String accessTokenStoreTable = OAuthConstants.ACCESS_TOKEN_STORE_TABLE; Connection connection = IdentityDatabaseUtil.getDBConnection(); PreparedStatement ps = null; if (tokens.length > 1) { try { List<String> oldTokens = new ArrayList<>(); connection.setAutoCommit(false); String sqlQuery = SQLQueries.REVOKE_ACCESS_TOKEN.replace(IDN_OAUTH2_ACCESS_TOKEN, accessTokenStoreTable); ps = connection.prepareStatement(sqlQuery); for (String token : tokens) { ps.setString(1, OAuthConstants.TokenStates.TOKEN_STATE_REVOKED); ps.setString(2, UUID.randomUUID().toString()); ps.setString(3, getHashingPersistenceProcessor().getProcessedAccessTokenIdentifier(token)); ps.addBatch(); oldTokens.add(getHashingPersistenceProcessor().getProcessedAccessTokenIdentifier(token)); } ps.executeBatch(); connection.commit(); // To revoke request objects which have persisted against the access token. OAuth2TokenUtil.postUpdateAccessTokens(Arrays.asList(tokens), OAuthConstants.TokenStates.TOKEN_STATE_REVOKED); if (isTokenCleanupFeatureEnabled) { oldTokenCleanupObject.cleanupTokensInBatch(oldTokens, connection); } connection.commit(); } catch (SQLException e) { IdentityDatabaseUtil.rollBack(connection); throw new IdentityOAuth2Exception( "Error occurred while revoking Access Tokens : " + Arrays.toString(tokens), e); } finally { IdentityDatabaseUtil.closeAllConnections(connection, null, ps); } } if (tokens.length == 1) { try { connection.setAutoCommit(true); String sqlQuery = SQLQueries.REVOKE_ACCESS_TOKEN.replace(IDN_OAUTH2_ACCESS_TOKEN, accessTokenStoreTable); ps = connection.prepareStatement(sqlQuery); ps.setString(1, OAuthConstants.TokenStates.TOKEN_STATE_REVOKED); ps.setString(2, UUID.randomUUID().toString()); ps.setString(3, getHashingPersistenceProcessor().getProcessedAccessTokenIdentifier(tokens[0])); ps.executeUpdate(); // To revoke request objects which have persisted against the access token. OAuth2TokenUtil.postUpdateAccessTokens(Arrays.asList(tokens), OAuthConstants.TokenStates.TOKEN_STATE_REVOKED); if (isTokenCleanupFeatureEnabled) { oldTokenCleanupObject.cleanupTokenByTokenValue( getHashingPersistenceProcessor().getProcessedAccessTokenIdentifier(tokens[0]), connection); } } catch (SQLException e) { // IdentityDatabaseUtil.rollBack(connection); throw new IdentityOAuth2Exception( "Error occurred while revoking Access Token : " + Arrays.toString(tokens), e); } finally { IdentityDatabaseUtil.closeAllConnections(connection, null, ps); } } }
From source file:org.wso2.carbon.identity.oauth2.dao.AccessTokenDAOImpl.java
@Override public void revokeAccessTokensIndividually(String[] tokens) throws IdentityOAuth2Exception { List<String> accessTokenId = new ArrayList<>(); if (log.isDebugEnabled()) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { StringBuilder stringBuilder = new StringBuilder(); for (String token : tokens) { stringBuilder.append(DigestUtils.sha256Hex(token)).append(" "); }//w w w . jav a 2 s .com log.debug("Revoking access tokens(hashed): " + stringBuilder.toString()); } else { log.debug("Revoking access tokens in individual mode"); } } Connection connection = IdentityDatabaseUtil.getDBConnection(); PreparedStatement ps = null; try { connection.setAutoCommit(false); for (String token : tokens) { String sqlQuery = OAuth2Util.getTokenPartitionedSqlByToken(SQLQueries.REVOKE_ACCESS_TOKEN, token); ps = connection.prepareStatement(sqlQuery); ps.setString(1, OAuthConstants.TokenStates.TOKEN_STATE_REVOKED); ps.setString(2, UUID.randomUUID().toString()); ps.setString(3, getHashingPersistenceProcessor().getProcessedAccessTokenIdentifier(token)); int count = ps.executeUpdate(); if (log.isDebugEnabled()) { log.debug("Number of rows being updated : " + count); } accessTokenId.add(getTokenIdByAccessToken(token)); } connection.commit(); // To revoke request objects which have persisted against the access token. if (accessTokenId.size() > 0) { OAuth2TokenUtil.postUpdateAccessTokens(accessTokenId, OAuthConstants.TokenStates.TOKEN_STATE_REVOKED); } if (isTokenCleanupFeatureEnabled) { for (String token : tokens) { oldTokenCleanupObject.cleanupTokenByTokenValue( getHashingPersistenceProcessor().getProcessedAccessTokenIdentifier(token), connection); } } connection.commit(); } catch (SQLException e) { IdentityDatabaseUtil.rollBack(connection); throw new IdentityOAuth2Exception( "Error occurred while revoking Access Token : " + Arrays.toString(tokens), e); } finally { IdentityDatabaseUtil.closeAllConnections(connection, null, ps); } }
From source file:org.wso2.carbon.identity.oauth2.dao.AccessTokenDAOImpl.java
/** * This method is used invalidate the existing token and generate a new toke within one DB transaction. * * @param oldAccessTokenId access token need to be updated. * @param tokenState token state before generating new token. * @param consumerKey consumer key of the existing token * @param tokenStateId new token state id to be updated * @param accessTokenDO new access token details * @param userStoreDomain user store domain which is related to this consumer * @throws IdentityOAuth2Exception/*from w ww .ja v a2 s . c o m*/ */ @Override public void invalidateAndCreateNewAccessToken(String oldAccessTokenId, String tokenState, String consumerKey, String tokenStateId, AccessTokenDO accessTokenDO, String userStoreDomain) throws IdentityOAuth2Exception { if (log.isDebugEnabled()) { if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Invalidating access token with id: " + oldAccessTokenId + " and creating new access token" + "(hashed): " + DigestUtils.sha256Hex(accessTokenDO.getAccessToken()) + " for client: " + consumerKey + " user: " + accessTokenDO.getAuthzUser().toString() + " scope: " + Arrays.toString(accessTokenDO.getScope())); } else { log.debug("Invalidating and creating new access token for client: " + consumerKey + " user: " + accessTokenDO.getAuthzUser().toString() + " scope: " + Arrays.toString(accessTokenDO.getScope())); } } Connection connection = IdentityDatabaseUtil.getDBConnection(); try { connection.setAutoCommit(false); // update existing token as inactive updateAccessTokenState(connection, oldAccessTokenId, tokenState, tokenStateId, userStoreDomain); String newAccessToken = accessTokenDO.getAccessToken(); // store new token in the DB insertAccessToken(newAccessToken, consumerKey, accessTokenDO, connection, userStoreDomain); // update new access token against authorization code if token obtained via authorization code grant type updateTokenIdIfAutzCodeGrantType(oldAccessTokenId, accessTokenDO.getTokenId(), connection); // commit both transactions connection.commit(); // Post refresh access token event OAuth2TokenUtil.postRefreshAccessToken(oldAccessTokenId, accessTokenDO.getTokenId(), tokenState); if (isTokenCleanupFeatureEnabled && oldAccessTokenId != null) { oldTokenCleanupObject.cleanupTokenByTokenId(oldAccessTokenId, connection); } connection.commit(); } catch (SQLException e) { String errorMsg = "Error while regenerating access token"; throw new IdentityOAuth2Exception(errorMsg, e); } finally { IdentityDatabaseUtil.closeConnection(connection); } }
From source file:org.wso2.carbon.identity.oauth2.dao.AccessTokenDAOImpl.java
/** * Retrieves token id of the given token. * * @param token/*from ww w . j a v a 2 s . c o m*/ * @return * @throws IdentityOAuth2Exception */ @Override public String getTokenIdByAccessToken(String token) throws IdentityOAuth2Exception { if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) { log.debug("Retrieving id of access token(hashed): " + DigestUtils.sha256Hex(token)); } String tokenId = getTokenIdByAccessToken(token, IdentityUtil.getPrimaryDomainName()); if (tokenId == null && OAuth2Util.checkAccessTokenPartitioningEnabled() && OAuth2Util.checkUserNameAssertionEnabled()) { Map<String, String> availableDomainMappings = OAuth2Util.getAvailableUserStoreDomainMappings(); for (Map.Entry<String, String> availableDomainMapping : availableDomainMappings.entrySet()) { tokenId = getTokenIdByAccessToken(token, availableDomainMapping.getKey()); if (tokenId != null) { break; } } } return tokenId; }