Search in sources :

Example 21 with IdentityOAuth2ScopeException

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

the class ScopeMgtDAOTest method getScopesWithPagination.

@Test(dataProvider = "getScopesWithPaginationDataProvider")
public void getScopesWithPagination(List<Object> scopes, int tenantId) throws SQLException, IdentityOAuth2ScopeException {
    try (Connection connection = DAOUtils.getConnection(DB_NAME)) {
        mockStatic(IdentityDatabaseUtil.class);
        addScopes(scopes, tenantId);
        when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
        when(IdentityDatabaseUtil.getDBConnection(false)).thenReturn(connection);
        Set<Scope> scopesList = oAuthScopeDAO.getScopesWithPagination(1, 2, tenantId);
        assertTrue(scopesList != null && scopesList.size() == 2, "Failed to retrieve scopes with pagination.");
        // Clean after test
        deleteScopes(scopes, tenantId);
    }
}
Also used : Scope(org.wso2.carbon.identity.oauth2.bean.Scope) Connection(java.sql.Connection) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) IdentityBaseTest(org.wso2.carbon.identity.testutil.IdentityBaseTest)

Example 22 with IdentityOAuth2ScopeException

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

the class OAuth2ScopeService method deleteScope.

/**
 * Delete the scope for the given scope ID
 *
 * @param name Scope ID of the scope which need to get deleted
 * @throws IdentityOAuth2ScopeException
 */
public void deleteScope(String name) throws IdentityOAuth2ScopeException {
    validateScopeName(name);
    // Check whether a scope exists with the provided scope name which to be deleted.
    validateScopeExistence(name);
    int tenantID = Oauth2ScopeUtils.getTenantID();
    OAuthScopeCache.getInstance().clearCacheEntry(new OAuthScopeCacheKey(name), tenantID);
    try {
        OAuthTokenPersistenceFactory.getInstance().getOAuthScopeDAO().deleteScopeByName(name, tenantID);
        if (log.isDebugEnabled()) {
            log.debug("Scope: " + name + " is deleted from the database.");
        }
    } catch (IdentityOAuth2ScopeServerException e) {
        throw Oauth2ScopeUtils.generateServerException(Oauth2ScopeConstants.ErrorMessages.ERROR_CODE_FAILED_TO_DELETE_SCOPE_BY_NAME, name, e);
    }
}
Also used : OAuthScopeCacheKey(org.wso2.carbon.identity.oauth.cache.OAuthScopeCacheKey)

Example 23 with IdentityOAuth2ScopeException

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

the class OAuth2ScopeService method isScopeExists.

/**
 * Check the existence of a scope
 *
 * @param name Name of the scope
 * @return true if scope with the given scope name exists
 * @throws IdentityOAuth2ScopeException
 */
public boolean isScopeExists(String name) throws IdentityOAuth2ScopeException {
    boolean isScopeExists;
    int tenantID = Oauth2ScopeUtils.getTenantID();
    if (name == null) {
        throw Oauth2ScopeUtils.generateClientException(Oauth2ScopeConstants.ErrorMessages.ERROR_CODE_BAD_REQUEST_SCOPE_NAME_NOT_SPECIFIED, null);
    }
    Scope scopeFromCache = OAuthScopeCache.getInstance().getValueFromCache(new OAuthScopeCacheKey(name), tenantID);
    if (scopeFromCache != null) {
        isScopeExists = true;
    } else {
        try {
            isScopeExists = OAuthTokenPersistenceFactory.getInstance().getOAuthScopeDAO().isScopeExists(name, tenantID);
        } catch (IdentityOAuth2ScopeServerException e) {
            throw Oauth2ScopeUtils.generateServerException(Oauth2ScopeConstants.ErrorMessages.ERROR_CODE_FAILED_TO_GET_SCOPE_BY_NAME, name, e);
        }
    }
    return isScopeExists;
}
Also used : Scope(org.wso2.carbon.identity.oauth2.bean.Scope) OAuthScopeCacheKey(org.wso2.carbon.identity.oauth.cache.OAuthScopeCacheKey)

Example 24 with IdentityOAuth2ScopeException

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

the class OAuth2ScopeService method updateUserConsentForApplication.

/**
 * Update consent given for OAuth scopes by a user for a given application.
 *
 * @param userId            User Id.
 * @param appId             Application Id.
 * @param userTenantId      Tenant Id.
 * @param approvedScopes    List of approved scopes.
 * @param deniedScopes      List of denied scopes.
 * @throws IdentityOAuth2ScopeException
 */
public void updateUserConsentForApplication(String userId, String appId, int userTenantId, List<String> approvedScopes, List<String> deniedScopes) throws IdentityOAuth2ScopeException {
    validateUserId(userId);
    validateAppId(appId);
    try {
        UserApplicationScopeConsentDO updatedUserApplicationScopeConsents = new UserApplicationScopeConsentDO(appId, approvedScopes, deniedScopes);
        UserApplicationScopeConsentDO existingConsent = OAuthTokenPersistenceFactory.getInstance().getOAuthUserConsentedScopesDAO().getUserConsentForApplication(userId, updatedUserApplicationScopeConsents.getAppId(), userTenantId);
        UserApplicationScopeConsentDO consentsToBeUpdated = getConsentsToBeUpdated(existingConsent, updatedUserApplicationScopeConsents);
        UserApplicationScopeConsentDO consentsToBeAdded = getConsentsToBeAdded(consentsToBeUpdated, updatedUserApplicationScopeConsents);
        OAuthTokenPersistenceFactory.getInstance().getOAuthUserConsentedScopesDAO().updateExistingConsentForApplication(userId, appId, userTenantId, consentsToBeAdded, consentsToBeUpdated);
        if (log.isDebugEnabled()) {
            log.debug("Successfully updated the user consent for OAuth scopes for user : " + userId + " and application : " + appId + " in tenant with Id : " + userTenantId);
        }
    } catch (IdentityOAuth2ScopeConsentException e) {
        Oauth2ScopeConstants.ErrorMessages error = Oauth2ScopeConstants.ErrorMessages.ERROR_CODE_FAILED_TO_UPDATE_USER_CONSENT_FOR_APP;
        String msg = String.format(error.getMessage(), userId, appId, userTenantId);
        throw new IdentityOAuth2ScopeServerException(error.getCode(), msg, e);
    }
}
Also used : UserApplicationScopeConsentDO(org.wso2.carbon.identity.oauth2.model.UserApplicationScopeConsentDO)

Example 25 with IdentityOAuth2ScopeException

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

the class EndpointUtil method setConsentRequiredScopesToOAuthParams.

private static void setConsentRequiredScopesToOAuthParams(AuthenticatedUser user, OAuth2Parameters params) throws OAuthSystemException {
    try {
        String consentRequiredScopes = StringUtils.EMPTY;
        List<String> allowedOAuthScopes = getAllowedOAuthScopes(params);
        if (user != null && !isPromptContainsConsent(params)) {
            String userId = getUserIdOfAuthenticatedUser(user);
            String appId = getAppIdFromClientId(params.getClientId());
            OAuth2ScopeConsentResponse existingUserConsent = oAuth2ScopeService.getUserConsentForApp(userId, appId, IdentityTenantUtil.getTenantId(user.getTenantDomain()));
            if (existingUserConsent != null) {
                if (CollectionUtils.isNotEmpty(existingUserConsent.getApprovedScopes())) {
                    allowedOAuthScopes.removeAll(existingUserConsent.getApprovedScopes());
                }
            }
        }
        if (CollectionUtils.isNotEmpty(allowedOAuthScopes)) {
            // Filter out internal scopes to be validated.
            String[] requestedScopes = Oauth2ScopeUtils.getRequestedScopes(allowedOAuthScopes.toArray(new String[0]));
            if (ArrayUtils.isNotEmpty(requestedScopes)) {
                // Remove the filtered internal scopes from the allowedOAuthScopes list.
                allowedOAuthScopes.removeAll(Arrays.asList(requestedScopes));
                JDBCPermissionBasedInternalScopeValidator scopeValidator = new JDBCPermissionBasedInternalScopeValidator();
                String[] validatedScope = scopeValidator.validateScope(requestedScopes, user, params.getClientId());
                // Filter out requested scopes from the validated scope array.
                for (String scope : requestedScopes) {
                    if (ArrayUtils.contains(validatedScope, scope)) {
                        allowedOAuthScopes.add(scope);
                    }
                }
            }
            params.setConsentRequiredScopes(new HashSet<>(allowedOAuthScopes));
            consentRequiredScopes = String.join(" ", allowedOAuthScopes).trim();
        }
        if (log.isDebugEnabled()) {
            log.debug("Consent required scopes : " + consentRequiredScopes + " for request from client : " + params.getClientId());
        }
    } catch (IdentityOAuth2ScopeException e) {
        throw new OAuthSystemException("Error occurred while retrieving user consents OAuth scopes.");
    }
}
Also used : OAuth2ScopeConsentResponse(org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse) JDBCPermissionBasedInternalScopeValidator(org.wso2.carbon.identity.oauth2.validators.JDBCPermissionBasedInternalScopeValidator) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) IdentityOAuth2ScopeException(org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeException)

Aggregations

Scope (org.wso2.carbon.identity.oauth2.bean.Scope)14 Test (org.testng.annotations.Test)12 IdentityOAuth2ScopeException (org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeException)12 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)11 Connection (java.sql.Connection)9 IdentityOAuth2ScopeClientException (org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeClientException)8 IdentityBaseTest (org.wso2.carbon.identity.testutil.IdentityBaseTest)8 OAuthScopeCacheKey (org.wso2.carbon.identity.oauth.cache.OAuthScopeCacheKey)6 DataProvider (org.testng.annotations.DataProvider)5 UserApplicationScopeConsentDO (org.wso2.carbon.identity.oauth2.model.UserApplicationScopeConsentDO)5 ScopeDTO (org.wso2.carbon.identity.oauth.scope.endpoint.dto.ScopeDTO)3 ScopeEndpointException (org.wso2.carbon.identity.oauth.scope.endpoint.exceptions.ScopeEndpointException)3 PowerMockIdentityBaseTest (org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)3 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)2 ErrorDTO (org.wso2.carbon.identity.oauth.scope.endpoint.dto.ErrorDTO)2 OAuth2ScopeConsentResponse (org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse)2 SQLException (java.sql.SQLException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1