Search in sources :

Example 56 with OAuthSystemException

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

the class EndpointUtil method getAllowedOAuthScopes.

private static List<String> getAllowedOAuthScopes(OAuth2Parameters params) throws OAuthSystemException {
    Set<String> allowedScopes = params.getScopes();
    List<String> allowedOAuthScopes = new ArrayList<>();
    if (CollectionUtils.isNotEmpty(allowedScopes)) {
        try {
            startTenantFlow(params.getTenantDomain());
            /* If DropUnregisteredScopes scopes config is enabled
             then any unregistered scopes(excluding internal scopes
             and allowed scopes) is be dropped. Therefore they will
             not be shown in the user consent screen.*/
            if (oauthServerConfiguration.isDropUnregisteredScopes()) {
                if (log.isDebugEnabled()) {
                    log.debug("DropUnregisteredScopes config is enabled. Attempting to drop unregistered scopes.");
                }
                allowedScopes = dropUnregisteredScopes(params);
            }
            // Get registered OIDC scopes.
            String[] oidcScopes = oAuthAdminService.getScopeNames();
            List<String> oidcScopeList = new ArrayList<>(Arrays.asList(oidcScopes));
            for (String scope : allowedScopes) {
                if (!oidcScopeList.contains(scope)) {
                    allowedOAuthScopes.add(scope);
                }
            }
        } catch (IdentityOAuthAdminException e) {
            throw new OAuthSystemException("Error while retrieving OIDC scopes.", e);
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Allowed OAuth scopes : " + allowedOAuthScopes.stream().collect(Collectors.joining(" ")) + " for client : " + params.getClientId());
    }
    return allowedOAuthScopes;
}
Also used : IdentityOAuthAdminException(org.wso2.carbon.identity.oauth.IdentityOAuthAdminException) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) ArrayList(java.util.ArrayList)

Example 57 with OAuthSystemException

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

the class EndpointUtil method getRegisteredScopes.

private static Set<String> getRegisteredScopes(Set<String> requestedScopes) throws OAuthSystemException {
    try {
        String requestedScopesStr = StringUtils.join(requestedScopes, " ");
        Set<String> registeredScopes = new HashSet<>();
        Set<Scope> registeredScopeSet = oAuth2ScopeService.getScopes(null, null, true, requestedScopesStr);
        registeredScopeSet.forEach(scope -> registeredScopes.add(scope.getName()));
        return registeredScopes;
    } catch (IdentityOAuth2ScopeServerException e) {
        throw new OAuthSystemException("Error occurred while retrieving registered scopes.", e);
    }
}
Also used : IdentityOAuth2ScopeServerException(org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeServerException) Scope(org.wso2.carbon.identity.oauth2.bean.Scope) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) HashSet(java.util.HashSet)

Example 58 with OAuthSystemException

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

the class EndpointUtil method getUserConsentURL.

/**
 * Returns the consent page URL.
 *
 * @param params            OAuth2 Parameters.
 * @param loggedInUser      The logged in user
 * @param isOIDC            Whether the flow is an OIDC or not.
 * @param oAuthMessage      oAuth Message.
 * @return                  The consent url.
 */
public static String getUserConsentURL(OAuth2Parameters params, String loggedInUser, String sessionDataKey, boolean isOIDC, OAuthMessage oAuthMessage) throws OAuthSystemException {
    String queryString = "";
    if (log.isDebugEnabled()) {
        log.debug("Received Session Data Key is :  " + sessionDataKey);
        if (params == null) {
            log.debug("Received OAuth2 params are Null for UserConsentURL");
        }
    }
    SessionDataCache sessionDataCache = SessionDataCache.getInstance();
    SessionDataCacheEntry entry;
    if (oAuthMessage != null) {
        entry = oAuthMessage.getResultFromLogin();
    } else {
        entry = sessionDataCache.getValueFromCache(new SessionDataCacheKey(sessionDataKey));
    }
    AuthenticatedUser user = null;
    String consentPage = null;
    String sessionDataKeyConsent = UUID.randomUUID().toString();
    try {
        if (entry != null && entry.getQueryString() != null) {
            if (entry.getQueryString().contains(REQUEST_URI) && params != null) {
                // When request_uri requests come without redirect_uri, we need to append it to the SPQueryParams
                // to be used in storing consent data
                entry.setQueryString(entry.getQueryString() + "&" + PROP_REDIRECT_URI + "=" + params.getRedirectURI());
            }
            queryString = URLEncoder.encode(entry.getQueryString(), UTF_8);
        }
        if (isOIDC) {
            consentPage = OAuth2Util.OAuthURL.getOIDCConsentPageUrl();
        } else {
            consentPage = OAuth2Util.OAuthURL.getOAuth2ConsentPageUrl();
        }
        if (params != null) {
            consentPage += "?" + OAuthConstants.OIDC_LOGGED_IN_USER + "=" + URLEncoder.encode(loggedInUser, UTF_8) + "&application=";
            if (StringUtils.isNotEmpty(params.getDisplayName())) {
                consentPage += URLEncoder.encode(params.getDisplayName(), UTF_8);
            } else {
                consentPage += URLEncoder.encode(params.getApplicationName(), UTF_8);
            }
            consentPage += "&tenantDomain=" + getSPTenantDomainFromClientId(params.getClientId());
            if (entry != null) {
                user = entry.getLoggedInUser();
            }
            setConsentRequiredScopesToOAuthParams(user, params);
            Set<String> consentRequiredScopesSet = params.getConsentRequiredScopes();
            String consentRequiredScopes = StringUtils.EMPTY;
            if (CollectionUtils.isNotEmpty(consentRequiredScopesSet)) {
                consentRequiredScopes = String.join(" ", consentRequiredScopesSet).trim();
            }
            consentPage = consentPage + "&" + OAuthConstants.OAuth20Params.SCOPE + "=" + URLEncoder.encode(consentRequiredScopes, UTF_8) + "&" + OAuthConstants.SESSION_DATA_KEY_CONSENT + "=" + URLEncoder.encode(sessionDataKeyConsent, UTF_8) + "&" + "&spQueryParams=" + queryString;
            if (entry != null) {
                consentPage = FrameworkUtils.getRedirectURLWithFilteredParams(consentPage, entry.getEndpointParams());
                entry.setValidityPeriod(TimeUnit.MINUTES.toNanos(IdentityUtil.getTempDataCleanUpTimeout()));
                sessionDataCache.addToCache(new SessionDataCacheKey(sessionDataKeyConsent), entry);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Cache Entry is Null from SessionDataCache.");
                }
            }
        } else {
            throw new OAuthSystemException("Error while retrieving the application name");
        }
    } catch (UnsupportedEncodingException e) {
        throw new OAuthSystemException("Error while encoding the url", e);
    }
    return consentPage;
}
Also used : SessionDataCache(org.wso2.carbon.identity.oauth.cache.SessionDataCache) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) SessionDataCacheEntry(org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Example 59 with OAuthSystemException

use of org.apache.oltu.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 60 with OAuthSystemException

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

the class OAuth2AuthzEndpoint method handleUserConsent.

private String handleUserConsent(OAuthMessage oAuthMessage, String consent, OIDCSessionState sessionState) throws OAuthSystemException {
    OAuth2Parameters oauth2Params = getOauth2Params(oAuthMessage);
    storeUserConsent(oAuthMessage, consent);
    OAuthResponse oauthResponse;
    String responseType = oauth2Params.getResponseType();
    HttpRequestHeaderHandler httpRequestHeaderHandler = new HttpRequestHeaderHandler(oAuthMessage.getRequest());
    // authorizing the request
    OAuth2AuthorizeRespDTO authzRespDTO = authorize(oauth2Params, oAuthMessage.getSessionDataCacheEntry(), httpRequestHeaderHandler);
    if (isSuccessfulAuthorization(authzRespDTO)) {
        oauthResponse = handleSuccessAuthorization(oAuthMessage, sessionState, oauth2Params, responseType, authzRespDTO);
    } else if (isFailureAuthorizationWithErorrCode(authzRespDTO)) {
        // Authorization failure due to various reasons
        return handleFailureAuthorization(oAuthMessage, sessionState, oauth2Params, authzRespDTO);
    } else {
        // Authorization failure due to various reasons
        return handleServerErrorAuthorization(oAuthMessage, sessionState, oauth2Params);
    }
    // When response_mode equals to form_post, body parameter is passed back.
    if (isFormPostModeAndResponseBodyExists(oauth2Params, oauthResponse)) {
        return oauthResponse.getBody();
    } else {
        // as per the specification: http://openid.net/specs/openid-connect-core-1_0.html#HybridCallback
        if (hasIDTokenInResponseType(responseType)) {
            return buildOIDCResponseWithURIFragment(oauthResponse, authzRespDTO);
        } else {
            return appendAuthenticatedIDPs(oAuthMessage.getSessionDataCacheEntry(), oauthResponse.getLocationUri());
        }
    }
}
Also used : OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) HttpRequestHeaderHandler(org.wso2.carbon.identity.oauth2.model.HttpRequestHeaderHandler) OAuth2AuthorizeRespDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse)

Aggregations

OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)98 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)53 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)49 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)49 IOException (java.io.IOException)38 Request (okhttp3.Request)27 Response (okhttp3.Response)27 OAuthJSONAccessTokenResponse (org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse)21 URI (java.net.URI)17 Builder (okhttp3.Request.Builder)17 OAuthBearerClientRequest (org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest)16 Map (java.util.Map)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)13 MD5Generator (org.apache.oltu.oauth2.as.issuer.MD5Generator)12 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)12 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)12 Path (javax.ws.rs.Path)11