Search in sources :

Example 6 with IdentityOAuth2ScopeException

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

the class OAuth2ScopeService method updateScope.

/**
 * Update the scope of the given scope ID
 *
 * @param updatedScope details of updated scope
 * @return updated scope
 * @throws IdentityOAuth2ScopeException
 */
public Scope updateScope(Scope updatedScope) throws IdentityOAuth2ScopeException {
    updateScopePreValidation(updatedScope);
    // Check whether a scope exists with the provided scope name which to be deleted.
    validateScopeExistence(updatedScope.getName());
    int tenantID = Oauth2ScopeUtils.getTenantID();
    try {
        OAuthTokenPersistenceFactory.getInstance().getOAuthScopeDAO().updateScopeByName(updatedScope, tenantID);
    } catch (IdentityOAuth2ScopeServerException e) {
        throw Oauth2ScopeUtils.generateServerException(Oauth2ScopeConstants.ErrorMessages.ERROR_CODE_FAILED_TO_UPDATE_SCOPE_BY_NAME, updatedScope.getName(), e);
    }
    OAuthScopeCache.getInstance().addToCache(new OAuthScopeCacheKey(updatedScope.getName()), updatedScope, tenantID);
    OIDCScopeClaimCache.getInstance().clearScopeClaimMap(tenantID);
    return updatedScope;
}
Also used : OAuthScopeCacheKey(org.wso2.carbon.identity.oauth.cache.OAuthScopeCacheKey)

Example 7 with IdentityOAuth2ScopeException

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

the class OAuth2ScopeService method addUserConsentForApplication.

/**
 * Add an OAuth scope consent given for an application by an user.
 *
 * @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 addUserConsentForApplication(String userId, String appId, int userTenantId, List<String> approvedScopes, List<String> deniedScopes) throws IdentityOAuth2ScopeException {
    validateUserId(userId);
    validateAppId(appId);
    try {
        UserApplicationScopeConsentDO userApplicationScopeConsents = new UserApplicationScopeConsentDO(appId, approvedScopes, deniedScopes);
        OAuthTokenPersistenceFactory.getInstance().getOAuthUserConsentedScopesDAO().addUserConsentForApplication(userId, userTenantId, userApplicationScopeConsents);
        if (log.isDebugEnabled()) {
            log.debug("Successfully added the user consent for OAuth scopes for user : " + userId + " and application name : " + appId + " in tenant with id : " + userTenantId);
        }
    } catch (IdentityOAuth2ScopeConsentException e) {
        Oauth2ScopeConstants.ErrorMessages error = Oauth2ScopeConstants.ErrorMessages.ERROR_CODE_FAILED_TO_ADD_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 8 with IdentityOAuth2ScopeException

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

the class OAuth2ScopeService method getUserConsentForApp.

/**
 * Get OAuth scope consent given for an application by the user.
 *
 * @param userId        User Id.
 * @param appId         Application Id.
 * @param userTenantId  Tenant Id.
 * @return  {@link OAuth2ScopeConsentResponse}.
 * @throws IdentityOAuth2ScopeException
 */
public OAuth2ScopeConsentResponse getUserConsentForApp(String userId, String appId, int userTenantId) throws IdentityOAuth2ScopeException {
    validateUserId(userId);
    validateAppId(appId);
    try {
        UserApplicationScopeConsentDO userConsent = OAuthTokenPersistenceFactory.getInstance().getOAuthUserConsentedScopesDAO().getUserConsentForApplication(userId, appId, userTenantId);
        OAuth2ScopeConsentResponse consentResponse = new OAuth2ScopeConsentResponse(userId, appId, userTenantId, userConsent.getApprovedScopes(), userConsent.getDeniedScopes());
        if (log.isDebugEnabled()) {
            log.debug("Successfully retrieved the user consent for userId : " + userId + " and appId: " + appId + " as approved scopes : " + userConsent.getApprovedScopes().stream().collect(Collectors.joining(" ")) + " and denied scopes : " + userConsent.getDeniedScopes().stream().collect(Collectors.joining(" ")));
        }
        return consentResponse;
    } catch (IdentityOAuth2ScopeConsentException e) {
        Oauth2ScopeConstants.ErrorMessages error = Oauth2ScopeConstants.ErrorMessages.ERROR_CODE_FAILED_TO_RETRIEVE_USER_CONSENTS_FOR_APP;
        String msg = String.format(error.getMessage(), userId, appId, userTenantId);
        throw new IdentityOAuth2ScopeServerException(error.getCode(), msg, e);
    }
}
Also used : OAuth2ScopeConsentResponse(org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse) UserApplicationScopeConsentDO(org.wso2.carbon.identity.oauth2.model.UserApplicationScopeConsentDO)

Example 9 with IdentityOAuth2ScopeException

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

the class EndpointUtil method storeOAuthScopeConsent.

/**
 * Store consent given for OAuth scopes by the user for the application.
 *
 * @param user                      Authenticated user.
 * @param params                    OAuth2 parameters.
 * @param overrideExistingConsent   True to override existing consent, otherwise merge the new consent with
 *                                  existing consent.
 * @throws OAuthSystemException
 */
public static void storeOAuthScopeConsent(AuthenticatedUser user, OAuth2Parameters params, boolean overrideExistingConsent) throws OAuthSystemException {
    try {
        Set<String> userApprovedScopesSet = params.getConsentRequiredScopes();
        if (CollectionUtils.isNotEmpty(userApprovedScopesSet)) {
            if (log.isDebugEnabled()) {
                log.debug("Storing user consent for approved scopes : " + userApprovedScopesSet.stream().collect(Collectors.joining(" ")) + " of client : " + params.getClientId());
            }
            List<String> userApprovedScopes = new ArrayList<>(userApprovedScopesSet);
            // Remove OIDC scopes.
            userApprovedScopes.removeAll(getOIDCScopeNames());
            String userId = getUserIdOfAuthenticatedUser(user);
            String appId = getAppIdFromClientId(params.getClientId());
            if (overrideExistingConsent) {
                if (log.isDebugEnabled()) {
                    log.debug("Overriding existing consents of the user : " + userId + " for application : " + appId);
                }
                oAuth2ScopeService.addUserConsentForApplication(userId, appId, IdentityTenantUtil.getTenantId(user.getTenantDomain()), userApprovedScopes, null);
            } else {
                boolean isUserConsentExist = oAuth2ScopeService.isUserHasAnExistingConsentForApp(userId, appId, IdentityTenantUtil.getTenantId(user.getTenantDomain()));
                if (isUserConsentExist) {
                    if (log.isDebugEnabled()) {
                        log.debug("Updating existing consents of the user : " + userId + " for application : " + appId);
                    }
                    oAuth2ScopeService.updateUserConsentForApplication(userId, appId, IdentityTenantUtil.getTenantId(user.getTenantDomain()), userApprovedScopes, null);
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Adding new consent to the user : " + userId + " for application : " + appId);
                    }
                    oAuth2ScopeService.addUserConsentForApplication(userId, appId, IdentityTenantUtil.getTenantId(user.getTenantDomain()), userApprovedScopes, null);
                }
            }
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                Map<String, Object> consentParams = new HashMap<>();
                consentParams.put("clientId", params.getClientId());
                consentParams.put("approvedScopes", userApprovedScopes);
                consentParams.put("user", userId);
                Map<String, Object> configs = new HashMap<>();
                configs.put("overrideExistingConsent", String.valueOf(overrideExistingConsent));
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, consentParams, OAuthConstants.LogConstants.SUCCESS, "Successfully persisted oauth scopes.", "persist-oauth-scope-consent", configs);
            }
        }
    } catch (IdentityOAuthAdminException e) {
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "System error occurred.", "persist-oauth-scope-consent", null);
        throw new OAuthSystemException("Error occurred while removing OIDC scopes from approved OAuth scopes.", e);
    } catch (IdentityOAuth2ScopeException e) {
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "System error occurred.", "persist-oauth-scope-consent", null);
        throw new OAuthSystemException("Error occurred while storing OAuth scope consent.", e);
    }
}
Also used : IdentityOAuthAdminException(org.wso2.carbon.identity.oauth.IdentityOAuthAdminException) HashMap(java.util.HashMap) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) ArrayList(java.util.ArrayList) IdentityOAuth2ScopeException(org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeException)

Example 10 with IdentityOAuth2ScopeException

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

the class ScopesApiServiceImpl method registerScope.

/**
 * Register a scope with the bindings.
 *
 * @param scope details of the scope to be registered
 * @return Response with the status of the registration.
 */
@Override
public Response registerScope(ScopeDTO scope) {
    Scope registeredScope = null;
    try {
        validateAddRequest(scope);
        registeredScope = ScopeUtils.getOAuth2ScopeService().registerScope(ScopeUtils.getScope(scope));
    } catch (IdentityOAuth2ScopeClientException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Client Error while registering scope \n" + scope.toString(), e);
        }
        if (Oauth2ScopeConstants.ErrorMessages.ERROR_CODE_CONFLICT_REQUEST_EXISTING_SCOPE.getCode().equals(e.getErrorCode())) {
            ScopeUtils.handleErrorResponse(Response.Status.CONFLICT, Response.Status.CONFLICT.getReasonPhrase(), e, false, LOG);
        } else if (Oauth2ScopeConstants.ErrorMessages.ERROR_CODE_NOT_AUTHORIZED_ADD_INTERNAL_SCOPE.getCode().equals(e.getErrorCode())) {
            ScopeUtils.handleErrorResponse(Response.Status.FORBIDDEN, Response.Status.FORBIDDEN.getReasonPhrase(), e, false, LOG);
        } else {
            ScopeUtils.handleErrorResponse(Response.Status.BAD_REQUEST, Response.Status.BAD_REQUEST.getReasonPhrase(), e, false, LOG);
        }
    } catch (IdentityOAuth2ScopeException e) {
        ScopeUtils.handleErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, Response.Status.INTERNAL_SERVER_ERROR.getReasonPhrase(), e, true, LOG);
    } catch (Throwable throwable) {
        ScopeUtils.handleErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, Response.Status.INTERNAL_SERVER_ERROR.getReasonPhrase(), throwable, true, LOG);
    }
    return Response.status(Response.Status.CREATED).location(buildURIForHeader(scope.getName())).entity(registeredScope).build();
}
Also used : Scope(org.wso2.carbon.identity.oauth2.bean.Scope) IdentityOAuth2ScopeClientException(org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeClientException) 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