Search in sources :

Example 1 with OAuth2Util.buildScopeString

use of org.wso2.carbon.identity.oauth2.util.OAuth2Util.buildScopeString in project carbon-apimgt by wso2.

the class SessionDataPublisherImpl method publishSessionTermination.

/**
 * Overridden method which implements the access token revocation
 * @param request termination request
 * @param context termination context
 * @param sessionContext termination sessionContext
 * @param params termination params
 */
@Override
public void publishSessionTermination(HttpServletRequest request, AuthenticationContext context, SessionContext sessionContext, Map<String, Object> params) {
    OAuthConsumerAppDTO[] appDTOs = new OAuthConsumerAppDTO[0];
    List<OAuthConsumerAppDTO> revokeAppList = new ArrayList<>();
    AuthenticatedUser authenticatedUser = (AuthenticatedUser) params.get(user);
    String username = authenticatedUser.getUserName();
    String tenantDomain = authenticatedUser.getTenantDomain();
    String userStoreDomain = authenticatedUser.getUserStoreDomain();
    AuthenticatedUser federatedUser;
    SystemApplicationDTO[] systemApplicationDTOS = new SystemApplicationDTO[0];
    if (authenticatedUser.isFederatedUser()) {
        try {
            federatedUser = buildAuthenticatedUser(authenticatedUser);
            authenticatedUser = federatedUser;
        } catch (IdentityOAuth2Exception e) {
            log.error("Error thrown while building authenticated user in logout flow for user " + authenticatedUser.getUserName(), e);
        }
    }
    SystemApplicationDAO systemApplicationDAO = new SystemApplicationDAO();
    try {
        systemApplicationDTOS = systemApplicationDAO.getApplications(tenantDomain);
        if (systemApplicationDTOS.length < 0) {
            if (log.isDebugEnabled()) {
                log.debug("The tenant: " + tenantDomain + " doesn't have any system apps");
            }
        }
    } catch (APIMgtDAOException e) {
        log.error("Error thrown while retrieving system applications for the tenant domain " + tenantDomain, e);
    }
    try {
        appDTOs = getAppsAuthorizedByUser(authenticatedUser);
        if (appDTOs.length > 0) {
            if (log.isDebugEnabled()) {
                log.debug("The user: " + authenticatedUser.getUserName() + " has " + appDTOs.length + " OAuth apps");
            }
        }
    } catch (IdentityOAuthAdminException e) {
        log.error("Error while retrieving applications authorized for the user " + authenticatedUser.getUserName(), e);
    }
    for (OAuthConsumerAppDTO appDTO : appDTOs) {
        for (SystemApplicationDTO systemApplicationDTO : systemApplicationDTOS) {
            if (StringUtils.equalsIgnoreCase(appDTO.getOauthConsumerKey(), systemApplicationDTO.getConsumerKey())) {
                revokeAppList.add(appDTO);
            }
        }
    }
    for (OAuthConsumerAppDTO appDTO : revokeAppList) {
        Set<AccessTokenDO> accessTokenDOs = null;
        try {
            // Retrieve all ACTIVE or EXPIRED access tokens for particular client authorized by this user
            accessTokenDOs = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getAccessTokens(appDTO.getOauthConsumerKey(), authenticatedUser, authenticatedUser.getUserStoreDomain(), true);
        } catch (IdentityOAuth2Exception e) {
            log.error("Error while retrieving access tokens for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
        }
        AuthenticatedUser authzUser;
        if (accessTokenDOs != null) {
            for (AccessTokenDO accessTokenDO : accessTokenDOs) {
                // Clear cache with AccessTokenDO
                authzUser = accessTokenDO.getAuthzUser();
                OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser, OAuth2Util.buildScopeString(accessTokenDO.getScope()), "NONE");
                OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser, OAuth2Util.buildScopeString(accessTokenDO.getScope()));
                OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser);
                OAuthUtil.clearOAuthCache(accessTokenDO.getAccessToken());
                Cache restApiTokenCache = CacheProvider.getRESTAPITokenCache();
                if (restApiTokenCache != null) {
                    restApiTokenCache.remove(accessTokenDO.getAccessToken());
                }
                AccessTokenDO scopedToken = null;
                try {
                    // Retrieve latest access token for particular client, user and scope combination if
                    // its ACTIVE or EXPIRED.
                    scopedToken = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getLatestAccessToken(appDTO.getOauthConsumerKey(), authenticatedUser, userStoreDomain, OAuth2Util.buildScopeString(accessTokenDO.getScope()), true);
                } catch (IdentityOAuth2Exception e) {
                    log.error("Error while retrieving scoped access tokens for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
                }
                if (scopedToken != null) {
                    // Revoking token from database
                    try {
                        OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().revokeAccessTokens(new String[] { scopedToken.getAccessToken() });
                    } catch (IdentityOAuth2Exception e) {
                        log.error("Error while revoking access tokens related for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
                    }
                    // Revoking the oauth consent from database.
                    try {
                        OAuthTokenPersistenceFactory.getInstance().getTokenManagementDAO().revokeOAuthConsentByApplicationAndUser(authzUser.getAuthenticatedSubjectIdentifier(), tenantDomain, username);
                    } catch (IdentityOAuth2Exception e) {
                        log.error("Error while revoking access tokens related for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
                    }
                }
            }
        }
    }
}
Also used : IdentityOAuthAdminException(org.wso2.carbon.identity.oauth.IdentityOAuthAdminException) APIMgtDAOException(org.wso2.carbon.apimgt.api.APIMgtDAOException) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) SystemApplicationDTO(org.wso2.carbon.apimgt.impl.dto.SystemApplicationDTO) SystemApplicationDAO(org.wso2.carbon.apimgt.impl.dao.SystemApplicationDAO) Cache(javax.cache.Cache)

Example 2 with OAuth2Util.buildScopeString

use of org.wso2.carbon.identity.oauth2.util.OAuth2Util.buildScopeString in project carbon-apimgt by wso2.

the class SessionDataPublisherImpl method getAppsAuthorizedByUser.

/**
 * Method to retrieve applications authorized for user
 * @param authenticatedUser authenticated user info
 * @return array of authorized applications
 * @throws IdentityOAuthAdminException exception
 */
private OAuthConsumerAppDTO[] getAppsAuthorizedByUser(AuthenticatedUser authenticatedUser) throws IdentityOAuthAdminException {
    OAuthAppDAO appDAO = new OAuthAppDAO();
    String tenantAwareusername = authenticatedUser.getUserName();
    String tenantDomain = authenticatedUser.getTenantDomain();
    String username = UserCoreUtil.addTenantDomainToEntry(tenantAwareusername, tenantDomain);
    String userStoreDomain = authenticatedUser.getUserStoreDomain();
    Set<String> clientIds;
    SystemApplicationDTO[] systemApplicationDTOS;
    SystemApplicationDAO systemApplicationDAO = new SystemApplicationDAO();
    Set<String> systemAppClientIds = new HashSet<>();
    try {
        systemApplicationDTOS = systemApplicationDAO.getApplications(tenantDomain);
        if (systemApplicationDTOS.length < 0) {
            if (log.isDebugEnabled()) {
                log.debug("The tenant: " + tenantDomain + " doesn't have any system apps");
            }
        } else {
            for (SystemApplicationDTO applicationDTO : systemApplicationDTOS) {
                try {
                    if (ApplicationMgtUtil.isUserAuthorized(applicationDTO.getName(), tenantAwareusername)) {
                        systemAppClientIds.add(applicationDTO.getConsumerKey());
                    }
                } catch (IdentityApplicationManagementException e) {
                    log.error("Error occurred while checking the authorization of the application " + applicationDTO.getName(), e);
                }
            }
        }
    } catch (APIMgtDAOException e) {
        log.error("Error thrown while retrieving system applications for the tenant domain " + tenantDomain, e);
    }
    clientIds = systemAppClientIds;
    Set<OAuthConsumerAppDTO> appDTOs = new HashSet<>();
    for (String clientId : clientIds) {
        Set<AccessTokenDO> accessTokenDOs;
        try {
            accessTokenDOs = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getAccessTokens(clientId, authenticatedUser, userStoreDomain, true);
        } catch (IdentityOAuth2Exception e) {
            throw handleError("Error occurred while retrieving access tokens issued for " + "Client ID : " + clientId + ", User ID : " + username, e);
        }
        if (!accessTokenDOs.isEmpty()) {
            Set<String> distinctClientUserScopeCombo = new HashSet<>();
            for (AccessTokenDO accessTokenDO : accessTokenDOs) {
                AccessTokenDO scopedToken;
                String scopeString = OAuth2Util.buildScopeString(accessTokenDO.getScope());
                try {
                    scopedToken = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getLatestAccessToken(clientId, authenticatedUser, userStoreDomain, scopeString, true);
                    if (scopedToken != null && !distinctClientUserScopeCombo.contains(clientId + ":" + username)) {
                        OAuthAppDO appDO;
                        try {
                            appDO = appDAO.getAppInformation(scopedToken.getConsumerKey());
                            appDTOs.add(buildConsumerAppDTO(appDO));
                            if (log.isDebugEnabled()) {
                                log.debug("Found App: " + appDO.getApplicationName() + " for user: " + username);
                            }
                        } catch (InvalidOAuthClientException e) {
                            String errorMsg = "Invalid Client ID : " + scopedToken.getConsumerKey();
                            log.error(errorMsg, e);
                            throw new IdentityOAuthAdminException(errorMsg);
                        } catch (IdentityOAuth2Exception e) {
                            String errorMsg = "Error occurred while retrieving app information " + "for Client ID : " + scopedToken.getConsumerKey();
                            log.error(errorMsg, e);
                            throw new IdentityOAuthAdminException(errorMsg);
                        }
                        distinctClientUserScopeCombo.add(clientId + ":" + username);
                    }
                } catch (IdentityOAuth2Exception e) {
                    String errorMsg = "Error occurred while retrieving latest access token issued for Client ID :" + " " + clientId + ", User ID : " + username + " and Scope : " + scopeString;
                    throw handleError(errorMsg, e);
                }
            }
        }
    }
    return appDTOs.toArray(new OAuthConsumerAppDTO[0]);
}
Also used : IdentityOAuthAdminException(org.wso2.carbon.identity.oauth.IdentityOAuthAdminException) APIMgtDAOException(org.wso2.carbon.apimgt.api.APIMgtDAOException) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OAuthAppDAO(org.wso2.carbon.identity.oauth.dao.OAuthAppDAO) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) SystemApplicationDTO(org.wso2.carbon.apimgt.impl.dto.SystemApplicationDTO) SystemApplicationDAO(org.wso2.carbon.apimgt.impl.dao.SystemApplicationDAO) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

Example 3 with OAuth2Util.buildScopeString

use of org.wso2.carbon.identity.oauth2.util.OAuth2Util.buildScopeString in project identity-inbound-auth-oauth by wso2-extensions.

the class AccessTokenDAOImpl method insertAccessToken.

private void insertAccessToken(String accessToken, String consumerKey, AccessTokenDO accessTokenDO, Connection connection, String userStoreDomain, int retryAttemptCounter) throws IdentityOAuth2Exception {
    if (!isPersistenceEnabled()) {
        return;
    }
    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.");
    }
    String accessTokenHash = accessToken;
    try {
        OauthTokenIssuer oauthTokenIssuer = OAuth2Util.getOAuthTokenIssuerForOAuthApp(consumerKey);
        // check for persist alias for the token type
        if (oauthTokenIssuer.usePersistedAccessTokenAlias()) {
            accessTokenHash = 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(accessTokenHash));
        }
        throw new IdentityOAuth2Exception("Error while getting access token hash.", e);
    } 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(accessTokenHash) + " for " + "client: " + consumerKey + " user: " + accessTokenDO.getAuthzUser().getLoggableUserId() + " scope: " + Arrays.toString(accessTokenDO.getScope()));
        } else {
            log.debug("Persisting access token for client: " + consumerKey + " user: " + accessTokenDO.getAuthzUser().getLoggableUserId() + " scope: " + Arrays.toString(accessTokenDO.getScope()));
        }
    }
    userStoreDomain = OAuth2Util.getSanitizedUserStoreDomain(userStoreDomain);
    String userDomain = OAuth2Util.getUserStoreDomain(accessTokenDO.getAuthzUser());
    String authenticatedIDP = OAuth2Util.getAuthenticatedIDP(accessTokenDO.getAuthzUser());
    PreparedStatement insertTokenPrepStmt = null;
    PreparedStatement addScopePrepStmt = null;
    if (log.isDebugEnabled()) {
        String username;
        if (isFederatedUser(accessTokenDO)) {
            username = accessTokenDO.getAuthzUser().getAuthenticatedSubjectIdentifier();
        } else {
            username = accessTokenDO.getAuthzUser().toFullQualifiedUsername();
        }
        log.debug("Userstore domain for user: " + username + " is " + userDomain);
    }
    String sql;
    if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
        sql = SQLQueries.INSERT_OAUTH2_ACCESS_TOKEN_WITH_IDP_NAME;
    } else {
        sql = SQLQueries.INSERT_OAUTH2_ACCESS_TOKEN;
    }
    sql = OAuth2Util.getTokenPartitionedSqlByUserStore(sql, userDomain);
    String sqlAddScopes = OAuth2Util.getTokenPartitionedSqlByUserStore(SQLQueries.INSERT_OAUTH2_TOKEN_SCOPE, userDomain);
    try {
        insertTokenPrepStmt = connection.prepareStatement(sql);
        insertTokenPrepStmt.setString(1, getPersistenceProcessor().getProcessedAccessTokenIdentifier(accessTokenHash));
        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(accessTokenHash));
        if (accessTokenDO.getRefreshToken() != null) {
            insertTokenPrepStmt.setString(17, getHashingPersistenceProcessor().getProcessedRefreshToken(accessTokenDO.getRefreshToken()));
        } else {
            insertTokenPrepStmt.setString(17, accessTokenDO.getRefreshToken());
        }
        boolean tokenBindingAvailable = isTokenBindingAvailable(accessTokenDO.getTokenBinding());
        if (tokenBindingAvailable) {
            insertTokenPrepStmt.setString(18, accessTokenDO.getTokenBinding().getBindingReference());
        } else {
            insertTokenPrepStmt.setString(18, NONE);
        }
        insertTokenPrepStmt.setString(19, getPersistenceProcessor().getProcessedClientId(consumerKey));
        if (OAuth2ServiceComponentHolder.isIDPIdColumnEnabled()) {
            insertTokenPrepStmt.setString(20, authenticatedIDP);
            insertTokenPrepStmt.setInt(21, tenantId);
        }
        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.addBatch();
            }
        }
        addScopePrepStmt.executeBatch();
        if (tokenBindingAvailable) {
            if (log.isDebugEnabled()) {
                log.debug("Storing token binding information" + " accessTokenId: " + accessTokenId + " bindingType: " + accessTokenDO.getTokenBinding().getBindingType() + " bindingRef: " + accessTokenDO.getTokenBinding().getBindingReference());
            }
            try (PreparedStatement preparedStatement = connection.prepareStatement(STORE_TOKEN_BINDING)) {
                preparedStatement.setString(1, accessTokenId);
                preparedStatement.setString(2, accessTokenDO.getTokenBinding().getBindingType());
                preparedStatement.setString(3, accessTokenDO.getTokenBinding().getBindingReference());
                preparedStatement.setString(4, accessTokenDO.getTokenBinding().getBindingValue());
                preparedStatement.setInt(5, tenantId);
                preparedStatement.execute();
            }
        }
        if (retryAttemptCounter > 0) {
            log.info("Successfully recovered 'CON_APP_KEY' constraint violation with the attempt : " + retryAttemptCounter);
        }
    } catch (SQLIntegrityConstraintViolationException e) {
        IdentityDatabaseUtil.rollbackTransaction(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.rollbackTransaction(connection);
        throw new IdentityOAuth2Exception("Invalid request", e);
    } catch (SQLException e) {
        IdentityDatabaseUtil.rollbackTransaction(connection);
        // 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);
        }
    } catch (Exception e) {
        IdentityDatabaseUtil.rollbackTransaction(connection);
        // SQLIntegrityConstraintViolationException or SQLException.
        if (StringUtils.containsIgnoreCase(e.getMessage(), "CON_APP_KEY") || (e.getCause() != null && StringUtils.containsIgnoreCase(e.getCause().getMessage(), "CON_APP_KEY")) || (e.getCause() != null && e.getCause().getCause() != null && StringUtils.containsIgnoreCase(e.getCause().getCause().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);
    }
}
Also used : OauthTokenIssuer(org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) SQLException(java.sql.SQLException) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) SQLIntegrityConstraintViolationException(java.sql.SQLIntegrityConstraintViolationException) PreparedStatement(java.sql.PreparedStatement) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException) DataAccessException(org.wso2.carbon.database.utils.jdbc.exceptions.DataAccessException) SQLIntegrityConstraintViolationException(java.sql.SQLIntegrityConstraintViolationException) SQLException(java.sql.SQLException) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException) DataTruncation(java.sql.DataTruncation)

Example 4 with OAuth2Util.buildScopeString

use of org.wso2.carbon.identity.oauth2.util.OAuth2Util.buildScopeString in project identity-inbound-auth-oauth by wso2-extensions.

the class AccessTokenDAOImpl method recoverFromConAppKeyConstraintViolation.

private void recoverFromConAppKeyConstraintViolation(String accessToken, String consumerKey, AccessTokenDO accessTokenDO, Connection connection, String userStoreDomain, int retryAttemptCounter) throws IdentityOAuth2Exception {
    try {
        connection.setAutoCommit(false);
        log.warn("Retry attempt to recover 'CON_APP_KEY' constraint violation : " + retryAttemptCounter);
        AccessTokenDO latestNonActiveToken = getLatestAccessTokenByState(connection, consumerKey, accessTokenDO.getAuthzUser(), userStoreDomain, OAuth2Util.buildScopeString(accessTokenDO.getScope()), false);
        AccessTokenDO latestActiveToken = getLatestAccessTokenByState(connection, consumerKey, accessTokenDO.getAuthzUser(), userStoreDomain, OAuth2Util.buildScopeString(accessTokenDO.getScope()), true);
        OauthTokenIssuer oauthTokenIssuer = OAuth2Util.getOAuthTokenIssuerForOAuthApp(consumerKey);
        if (latestActiveToken != null) {
            OAuthTokenReqMessageContext tokReqMsgCtx = OAuth2Util.getTokenRequestContext();
            // For JWT tokens, always issue a new token expiring the existing token.
            if (oauthTokenIssuer.renewAccessTokenPerRequest(tokReqMsgCtx)) {
                updateAccessTokenState(connection, latestActiveToken.getTokenId(), OAuthConstants.TokenStates.TOKEN_STATE_EXPIRED, UUID.randomUUID().toString(), userStoreDomain, latestActiveToken.getGrantType());
                // Update token issued time make this token as latest token & try to store it again.
                accessTokenDO.setIssuedTime(new Timestamp(new Date().getTime()));
                insertAccessToken(accessTokenDO.getAccessToken(), consumerKey, accessTokenDO, connection, userStoreDomain, retryAttemptCounter);
            } else if (OAuth2Util.getAccessTokenExpireMillis(latestActiveToken) != 0 && (latestNonActiveToken == null || latestActiveToken.getIssuedTime().after(latestNonActiveToken.getIssuedTime()))) {
                // If there is an active token in the database, it is not expired and it is the last issued
                // token, use the existing token. In here we can use existing token since we have a
                // synchronised communication.
                accessTokenDO.setTokenId(latestActiveToken.getTokenId());
                accessTokenDO.setAccessToken(latestActiveToken.getAccessToken());
                accessTokenDO.setRefreshToken(latestActiveToken.getRefreshToken());
                accessTokenDO.setIssuedTime(latestActiveToken.getIssuedTime());
                accessTokenDO.setRefreshTokenIssuedTime(latestActiveToken.getRefreshTokenIssuedTime());
                accessTokenDO.setValidityPeriodInMillis(latestActiveToken.getValidityPeriodInMillis());
                accessTokenDO.setRefreshTokenValidityPeriodInMillis(latestActiveToken.getRefreshTokenValidityPeriodInMillis());
                accessTokenDO.setTokenType(latestActiveToken.getTokenType());
                log.info("Successfully recovered 'CON_APP_KEY' constraint violation with the attempt : " + retryAttemptCounter);
            } else if (!(OAuth2Util.getAccessTokenExpireMillis(latestActiveToken) == 0)) {
                // If the last active token in the database is expired, update the token status in the database.
                updateAccessTokenState(connection, latestActiveToken.getTokenId(), OAuthConstants.TokenStates.TOKEN_STATE_EXPIRED, UUID.randomUUID().toString(), userStoreDomain, latestActiveToken.getGrantType());
                // Update token issued time make this token as latest token & try to store it again.
                accessTokenDO.setIssuedTime(new Timestamp(new Date().getTime()));
                insertAccessToken(accessToken, consumerKey, accessTokenDO, connection, userStoreDomain, retryAttemptCounter);
            } else {
                // Inactivate latest active token.
                updateAccessTokenState(connection, latestActiveToken.getTokenId(), OAuthConstants.TokenStates.TOKEN_STATE_INACTIVE, UUID.randomUUID().toString(), userStoreDomain, latestActiveToken.getGrantType());
                // Update token issued time make this token as latest token & try to store it again.
                accessTokenDO.setIssuedTime(new Timestamp(new Date().getTime()));
                insertAccessToken(accessToken, consumerKey, accessTokenDO, connection, userStoreDomain, retryAttemptCounter);
            }
        } else {
            // In this case another process already updated the latest active token to inactive.
            // Update token issued time make this token as latest token & try to store it again.
            accessTokenDO.setIssuedTime(new Timestamp(new Date().getTime()));
            insertAccessToken(accessToken, consumerKey, accessTokenDO, connection, userStoreDomain, retryAttemptCounter);
        }
        connection.commit();
    } catch (SQLException e) {
        try {
            if (connection != null) {
                connection.rollback();
            }
        } catch (SQLException e1) {
            throw new IdentityOAuth2Exception("An rolling back transactions error occurred while trying to " + "recover 'CON_APP_KEY' constraint violation. ", e1);
        }
        String errorMsg = "SQL error occurred while trying to recover 'CON_APP_KEY' constraint violation.";
        throw new IdentityOAuth2Exception(errorMsg, e);
    } catch (InvalidOAuthClientException e) {
        throw new IdentityOAuth2Exception("Error while retrieving oauth issuer for the app with clientId: " + consumerKey + ".", e);
    }
}
Also used : AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OauthTokenIssuer(org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) SQLException(java.sql.SQLException) OAuthTokenReqMessageContext(org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext) Timestamp(java.sql.Timestamp) Date(java.util.Date) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

Example 5 with OAuth2Util.buildScopeString

use of org.wso2.carbon.identity.oauth2.util.OAuth2Util.buildScopeString in project identity-inbound-auth-oauth by wso2-extensions.

the class ResponseTypeHandlerUtil method generateAccessToken.

/**
 * Generates access token for the given oauth issuer.
 *
 * @param oauthAuthzMsgCtx
 * @param cacheEnabled
 * @param oauthIssuerImpl
 * @return
 * @throws IdentityOAuth2Exception
 */
public static AccessTokenDO generateAccessToken(OAuthAuthzReqMessageContext oauthAuthzMsgCtx, boolean cacheEnabled, OauthTokenIssuer oauthIssuerImpl) throws IdentityOAuth2Exception {
    OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
    String scope = OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope());
    String consumerKey = authorizationReqDTO.getConsumerKey();
    String authorizedUserId;
    try {
        authorizedUserId = authorizationReqDTO.getUser().getUserId();
    } catch (UserIdNotFoundException e) {
        throw new IdentityOAuth2Exception("Error occurred while retrieving the user id for user: " + authorizationReqDTO.getUser().getLoggableUserId());
    }
    synchronized ((consumerKey + ":" + authorizedUserId + ":" + scope).intern()) {
        AccessTokenDO existingTokenBean = getExistingToken(oauthAuthzMsgCtx, authorizedUserId, cacheEnabled);
        // Return a new access token in each request when JWTTokenIssuer is used.
        if (isNotRenewAccessTokenPerRequest(oauthIssuerImpl, oauthAuthzMsgCtx)) {
            if (existingTokenBean != null) {
                // Revoke token if RenewTokenPerRequest configuration is enabled.
                if (OAuthServerConfiguration.getInstance().isTokenRenewalPerRequestEnabled()) {
                    if (log.isDebugEnabled()) {
                        log.debug("RenewTokenPerRequest configuration active. " + "Proceeding to revoke any existing active tokens for client Id: " + consumerKey + ", user: " + authorizationReqDTO.getUser().getLoggableUserId() + " and scope: " + scope + ".");
                    }
                    revokeExistingToken(existingTokenBean.getConsumerKey(), existingTokenBean.getAccessToken());
                    // When revoking the token state will be set as REVOKED.
                    // existingTokenBean.setTokenState(TOKEN_STATE_REVOKED) can be used instead of 'null' but
                    // then the token state will again be updated to EXPIRED when a new token is generated.
                    existingTokenBean = null;
                }
                // Return existing token if it is still valid.
                if (isAccessTokenValid(existingTokenBean)) {
                    return existingTokenBean;
                }
            }
            if (log.isDebugEnabled()) {
                log.debug("No active access token found for client Id: " + consumerKey + ", user: " + authorizationReqDTO.getUser().getLoggableUserId() + " and scope: " + scope + ". Therefore issuing new token");
            }
        }
        // Issue a new access token.
        return generateNewAccessToken(oauthAuthzMsgCtx, existingTokenBean, oauthIssuerImpl, authorizedUserId, cacheEnabled);
    }
}
Also used : AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuth2AuthorizeReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)

Aggregations

AccessTokenDO (org.wso2.carbon.identity.oauth2.model.AccessTokenDO)22 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)17 HashMap (java.util.HashMap)9 UserIdNotFoundException (org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)8 OAuthCacheKey (org.wso2.carbon.identity.oauth.cache.OAuthCacheKey)7 OAuth2AuthorizeReqDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO)7 AuthzCodeDO (org.wso2.carbon.identity.oauth2.model.AuthzCodeDO)7 Timestamp (java.sql.Timestamp)6 InvalidOAuthClientException (org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)6 OAuth2AccessTokenReqDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO)6 Date (java.util.Date)5 OAuth2AccessTokenRespDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO)5 ArrayList (java.util.ArrayList)4 Map (java.util.Map)4 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)4 IdentityApplicationManagementException (org.wso2.carbon.identity.application.common.IdentityApplicationManagementException)4 OAuthAppDO (org.wso2.carbon.identity.oauth.dao.OAuthAppDO)4 SQLException (java.sql.SQLException)3 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)3 Matchers.anyString (org.mockito.Matchers.anyString)3