Search in sources :

Example 46 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException 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 47 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method handlePostConsent.

private void handlePostConsent(OAuthMessage oAuthMessage) throws ConsentHandlingFailedException {
    OAuth2Parameters oauth2Params = getOauth2Params(oAuthMessage);
    String tenantDomain = EndpointUtil.getSPTenantDomainFromClientId(oauth2Params.getClientId());
    setSPAttributeToRequest(oAuthMessage.getRequest(), oauth2Params.getApplicationName(), tenantDomain);
    String spTenantDomain = oauth2Params.getTenantDomain();
    AuthenticatedUser loggedInUser = getLoggedInUser(oAuthMessage);
    String clientId = oauth2Params.getClientId();
    ServiceProvider serviceProvider;
    if (log.isDebugEnabled()) {
        log.debug("Initiating post user consent handling for user: " + loggedInUser.toFullQualifiedUsername() + " for client_id: " + clientId + " of tenantDomain: " + spTenantDomain);
    }
    try {
        if (isConsentHandlingFromFrameworkSkipped(oauth2Params)) {
            if (log.isDebugEnabled()) {
                log.debug("Consent handling from framework skipped for client_id: " + clientId + " of tenantDomain: " + spTenantDomain + " for user: " + loggedInUser.toFullQualifiedUsername() + ". " + "Therefore handling post consent is not applicable.");
            }
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                Map<String, Object> params = new HashMap<>();
                params.put("clientId", clientId);
                Map<String, Object> configs = new HashMap<>();
                configs.put("skipConsent", "true");
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Consent is disabled for the OAuth client.", "handle-consent", configs);
            }
            return;
        }
        List<Integer> approvedClaimIds = getUserConsentClaimIds(oAuthMessage);
        serviceProvider = getServiceProvider(clientId);
        /*
                With the current implementation of the SSOConsentService we need to send back the original
                ConsentClaimsData object we got during pre consent stage. Currently we are repeating the API call
                during post consent handling to get the original ConsentClaimsData object (Assuming there is no
                change in SP during pre-consent and post-consent).

                The API on the SSO Consent Service will be improved to avoid having to send the original
                ConsentClaimsData object.
             */
        ConsentClaimsData value = getConsentRequiredClaims(loggedInUser, serviceProvider, oauth2Params);
        /*
                It is needed to pitch the consent required claims with the OIDC claims. otherwise the consent of the
                the claims which are not in the OIDC claims will be saved as consent denied.
            */
        if (value != null) {
            // Remove the claims which dont have values given by the user.
            value.setRequestedClaims(removeConsentRequestedNullUserAttributes(value.getRequestedClaims(), loggedInUser.getUserAttributes(), spTenantDomain));
            List<ClaimMetaData> requestedOidcClaimsList = getRequestedOidcClaimsList(value, oauth2Params, spTenantDomain);
            value.setRequestedClaims(requestedOidcClaimsList);
        }
        // Call framework and create the consent receipt.
        if (log.isDebugEnabled()) {
            log.debug("Creating user consent receipt for user: " + loggedInUser.toFullQualifiedUsername() + " for client_id: " + clientId + " of tenantDomain: " + spTenantDomain);
        }
        Map<String, Object> params;
        if (hasPromptContainsConsent(oauth2Params)) {
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                params = new HashMap<>();
                params.put("clientId", clientId);
                params.put("prompt", oauth2Params.getPrompt());
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, null, "hand-over-to-consent-service", null);
            }
            getSSOConsentService().processConsent(approvedClaimIds, serviceProvider, loggedInUser, value, true);
        } else {
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                params = new HashMap<>();
                params.put("clientId", clientId);
                params.put("prompt", oauth2Params.getPrompt());
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, null, "hand-over-to-consent-service", null);
            }
            getSSOConsentService().processConsent(approvedClaimIds, serviceProvider, loggedInUser, value, false);
        }
    } catch (OAuthSystemException | SSOConsentServiceException e) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "System error occurred.", "process-consent", null);
        }
        String msg = "Error while processing consent of user: " + loggedInUser.toFullQualifiedUsername() + " for " + "client_id: " + clientId + " of tenantDomain: " + spTenantDomain;
        throw new ConsentHandlingFailedException(msg, e);
    } catch (ClaimMetadataException e) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, String.format("Error occurred while getting " + "claim mappings for %s.", OIDC_DIALECT), "process-consent", null);
        }
        throw new ConsentHandlingFailedException("Error while getting claim mappings for " + OIDC_DIALECT, e);
    } catch (RequestObjectException e) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, String.format("Error occurred while getting essential claims for the session data key : %s.", oauth2Params.getSessionDataKey()), "process-consent", null);
        }
        throw new ConsentHandlingFailedException("Error while getting essential claims for the session data key " + ": " + oauth2Params.getSessionDataKey(), e);
    }
}
Also used : RequestObjectException(org.wso2.carbon.identity.oauth2.RequestObjectException) ClaimMetadataException(org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) ConsentClaimsData(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.ConsentClaimsData) SSOConsentServiceException(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.exception.SSOConsentServiceException) ClaimMetaData(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.ClaimMetaData) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) ConsentHandlingFailedException(org.wso2.carbon.identity.oauth.endpoint.exception.ConsentHandlingFailedException) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) JSONObject(org.json.JSONObject)

Example 48 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.

the class CookieBasedTokenBinder method retrieveTokenBindingValueFromRequest.

private String retrieveTokenBindingValueFromRequest(HttpServletRequest request) throws OAuthSystemException {
    Cookie[] cookies = request.getCookies();
    if (ArrayUtils.isEmpty(cookies)) {
        return null;
    }
    Optional<Cookie> tokenBindingCookieOptional = Arrays.stream(cookies).filter(t -> COOKIE_NAME.equals(t.getName())).findAny();
    if (!tokenBindingCookieOptional.isPresent() || StringUtils.isBlank(tokenBindingCookieOptional.get().getValue())) {
        return null;
    }
    String tokenBindingValue = tokenBindingCookieOptional.get().getValue();
    boolean isTokenBindingValueValid;
    try {
        // Do we need additional validation here? like validate local user.
        isTokenBindingValueValid = OAuthTokenPersistenceFactory.getInstance().getTokenBindingMgtDAO().isTokenBindingExistsForBindingReference(OAuth2Util.getTokenBindingReference(tokenBindingValue));
    } catch (IdentityOAuth2Exception e) {
        throw new OAuthSystemException("Failed to check token binding reference existence", e);
    }
    return isTokenBindingValueValid ? tokenBindingValue : null;
}
Also used : SameSiteCookie(org.wso2.carbon.core.SameSiteCookie) ServletCookie(org.wso2.carbon.core.ServletCookie) Cookie(javax.servlet.http.Cookie) StringUtils(org.apache.commons.lang.StringUtils) Arrays(java.util.Arrays) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) HttpServletResponse(javax.servlet.http.HttpServletResponse) UUID(java.util.UUID) SameSiteCookie(org.wso2.carbon.core.SameSiteCookie) List(java.util.List) HttpServletRequest(javax.servlet.http.HttpServletRequest) AUTHORIZATION_CODE(org.wso2.carbon.identity.oauth.common.OAuthConstants.GrantTypes.AUTHORIZATION_CODE) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthTokenPersistenceFactory(org.wso2.carbon.identity.oauth2.dao.OAuthTokenPersistenceFactory) OAuth2AccessTokenReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) Optional(java.util.Optional) ServletCookie(org.wso2.carbon.core.ServletCookie) Cookie(javax.servlet.http.Cookie) Collections(java.util.Collections) COOKIE_BASED_TOKEN_BINDER(org.wso2.carbon.identity.oauth2.OAuth2Constants.TokenBinderType.COOKIE_BASED_TOKEN_BINDER) ArrayUtils(org.apache.commons.lang.ArrayUtils) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException)

Example 49 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.

the class SSOSessionBasedTokenBinder method isValidTokenBinding.

@Override
public boolean isValidTokenBinding(Object request, String bindingReference) {
    try {
        String sessionIdentifier = getTokenBindingValue((HttpServletRequest) request);
        if (StringUtils.isBlank(sessionIdentifier)) {
            if (log.isDebugEnabled()) {
                log.debug("CommonAuthId cookie is not found in the request.");
            }
            return false;
        }
        /* Retrieve session context information using sessionIdentifier in order to check the validity of
            commonAuthId cookie.*/
        SessionContext sessionContext = FrameworkUtils.getSessionContextFromCache(sessionIdentifier);
        if (sessionContext == null) {
            if (log.isDebugEnabled()) {
                log.debug("Session context is not found corresponding to the session identifier: " + sessionIdentifier);
            }
            return false;
        }
    } catch (OAuthSystemException e) {
        log.error("Error while getting the token binding value", e);
        return false;
    }
    return isValidTokenBinding(request, bindingReference, COMMONAUTH_COOKIE);
}
Also used : OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) SessionContext(org.wso2.carbon.identity.application.authentication.framework.context.SessionContext)

Example 50 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2Util method addTokenDOtoCache.

/**
 * There are cases where we store an 'alias' of the token returned to the client as the token inside IS.
 * For example, in the case of JWT access tokens we store the 'jti' claim in the database instead of the
 * actual JWT. Therefore we need to cache an AccessTokenDO with the stored token identifier.
 *
 * @param newTokenBean token DO to be added to the cache.
 */
public static void addTokenDOtoCache(AccessTokenDO newTokenBean) throws IdentityOAuth2Exception {
    OauthTokenIssuer tokenIssuer = null;
    try {
        tokenIssuer = OAuth2Util.getOAuthTokenIssuerForOAuthApp(newTokenBean.getConsumerKey());
        String tokenAlias = tokenIssuer.getAccessTokenHash(newTokenBean.getAccessToken());
        OAuthCacheKey accessTokenCacheKey = new OAuthCacheKey(tokenAlias);
        AccessTokenDO tokenDO = AccessTokenDO.clone(newTokenBean);
        tokenDO.setAccessToken(tokenAlias);
        OAuthCache.getInstance().addToCache(accessTokenCacheKey, tokenDO);
        if (log.isDebugEnabled()) {
            if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
                log.debug("Access token DO was added to OAuthCache with cache key: " + accessTokenCacheKey.getCacheKeyString());
            } else {
                log.debug("Access token DO was added to OAuthCache");
            }
        }
    } catch (OAuthSystemException e) {
        if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
            throw new IdentityOAuth2Exception("Error while getting the token alias from token issuer: " + tokenIssuer.toString() + " for the token: " + newTokenBean.getAccessToken(), e);
        } else {
            throw new IdentityOAuth2Exception("Error while getting the token alias from token issuer: " + tokenIssuer.toString(), e);
        }
    } catch (InvalidOAuthClientException e) {
        if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
            throw new IdentityOAuth2Exception("Error while getting the token issuer for the token: " + newTokenBean.getAccessToken(), e);
        } else {
            throw new IdentityOAuth2Exception("Error while getting the token issuer", e);
        }
    }
}
Also used : OauthTokenIssuer(org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OAuthCacheKey(org.wso2.carbon.identity.oauth.cache.OAuthCacheKey) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

Aggregations

OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)100 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)47 IOException (java.io.IOException)37 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)36 Request (okhttp3.Request)27 Response (okhttp3.Response)27 OAuthJSONAccessTokenResponse (org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse)20 Builder (okhttp3.Request.Builder)17 OAuthBearerClientRequest (org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest)17 Map (java.util.Map)15 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)15 OAuthClientResponse (org.apache.oltu.oauth2.client.response.OAuthClientResponse)14 MediaType (okhttp3.MediaType)13 RequestBody (okhttp3.RequestBody)13 TokenRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder)12 AuthenticationRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder)11 Path (javax.ws.rs.Path)10 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)9 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)9 HashMap (java.util.HashMap)8