Search in sources :

Example 41 with OAuthSystemException

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

the class ResponseTypeHandlerUtil method generateAuthorizationCode.

public static AuthzCodeDO generateAuthorizationCode(OAuthAuthzReqMessageContext oauthAuthzMsgCtx, boolean cacheEnabled, OauthTokenIssuer oauthIssuerImpl) throws IdentityOAuth2Exception {
    OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
    String authorizationCode;
    String codeId = UUID.randomUUID().toString();
    Timestamp timestamp = new Timestamp(new Date().getTime());
    long validityPeriod = OAuthServerConfiguration.getInstance().getAuthorizationCodeValidityPeriodInSeconds();
    // if a VALID callback is set through the callback handler, use
    // it instead of the default one
    long callbackValidityPeriod = oauthAuthzMsgCtx.getValidityPeriod();
    if ((callbackValidityPeriod != OAuthConstants.UNASSIGNED_VALIDITY_PERIOD) && callbackValidityPeriod > 0) {
        validityPeriod = callbackValidityPeriod;
    }
    // convert to milliseconds
    validityPeriod = validityPeriod * 1000;
    // set the validity period. this is needed by downstream handlers.
    // if this is set before - then this will override it by the calculated new value.
    oauthAuthzMsgCtx.setValidityPeriod(validityPeriod);
    oauthAuthzMsgCtx.setAuthorizationCodeValidityPeriod(validityPeriod);
    // set code issued time.this is needed by downstream handlers.
    oauthAuthzMsgCtx.setCodeIssuedTime(timestamp.getTime());
    if (authorizationReqDTO.getUser() != null && authorizationReqDTO.getUser().isFederatedUser()) {
        // if a federated user, treat the tenant domain as similar to application domain.
        authorizationReqDTO.getUser().setTenantDomain(authorizationReqDTO.getTenantDomain());
    }
    try {
        authorizationCode = oauthIssuerImpl.authorizationCode(oauthAuthzMsgCtx);
    } catch (OAuthSystemException e) {
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "System error occurred.", "issue-authz-code", null);
        throw new IdentityOAuth2Exception(e.getMessage(), e);
    }
    AuthzCodeDO authzCodeDO = new AuthzCodeDO(authorizationReqDTO.getUser(), oauthAuthzMsgCtx.getApprovedScope(), timestamp, validityPeriod, authorizationReqDTO.getCallbackUrl(), authorizationReqDTO.getConsumerKey(), authorizationCode, codeId, authorizationReqDTO.getPkceCodeChallenge(), authorizationReqDTO.getPkceCodeChallengeMethod());
    OAuthTokenPersistenceFactory.getInstance().getAuthorizationCodeDAO().insertAuthorizationCode(authorizationCode, authorizationReqDTO.getConsumerKey(), authorizationReqDTO.getCallbackUrl(), authzCodeDO);
    if (cacheEnabled) {
        // Cache the authz Code, here we prepend the client_key to avoid collisions with
        // AccessTokenDO instances. In database level, these are in two databases. But access
        // tokens and authorization codes are in a single cache.
        String cacheKeyString = OAuth2Util.buildCacheKeyStringForAuthzCode(authorizationReqDTO.getConsumerKey(), authorizationCode);
        OAuthCache.getInstance().addToCache(new OAuthCacheKey(cacheKeyString), authzCodeDO);
        if (log.isDebugEnabled()) {
            log.debug("Authorization Code info was added to the cache for client id : " + authorizationReqDTO.getConsumerKey());
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Issued Authorization Code to user : " + authorizationReqDTO.getUser() + ", Using the redirect url : " + authorizationReqDTO.getCallbackUrl() + ", Scope : " + OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope()) + ", validity period : " + validityPeriod);
    }
    if (LoggerUtils.isDiagnosticLogsEnabled()) {
        Map<String, Object> params = new HashMap<>();
        params.put("clientId", authorizationReqDTO.getConsumerKey());
        if (authorizationReqDTO.getUser() != null) {
            try {
                params.put("user", authorizationReqDTO.getUser().getUserId());
            } catch (UserIdNotFoundException e) {
                if (StringUtils.isNotBlank(authorizationReqDTO.getUser().getAuthenticatedSubjectIdentifier())) {
                    params.put("user", authorizationReqDTO.getUser().getAuthenticatedSubjectIdentifier().replaceAll(".", "*"));
                }
            }
        }
        params.put("requestedScopes", OAuth2Util.buildScopeString(authorizationReqDTO.getScopes()));
        params.put("redirectUri", authorizationReqDTO.getCallbackUrl());
        Map<String, Object> configs = new HashMap<>();
        configs.put("authzCodeValidityPeriod", String.valueOf(validityPeriod));
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Issued Authorization Code to user.", "issue-authz-code", configs);
    }
    return authzCodeDO;
}
Also used : HashMap(java.util.HashMap) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuth2AuthorizeReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) Timestamp(java.sql.Timestamp) Date(java.util.Date) OAuthCacheKey(org.wso2.carbon.identity.oauth.cache.OAuthCacheKey) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) AuthzCodeDO(org.wso2.carbon.identity.oauth2.model.AuthzCodeDO)

Example 42 with OAuthSystemException

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

the class SHA256Generator method generateValue.

@Override
public String generateValue(String value) throws OAuthSystemException {
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.reset();
        digest.update(value.getBytes(StandardCharsets.UTF_8));
        byte[] messageDigest = digest.digest();
        // Return the hex representation of the hash.
        return Hex.toHexString(messageDigest);
    } catch (Exception e) {
        throw new OAuthSystemException("Error while generating the token value.", e);
    }
}
Also used : OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) MessageDigest(java.security.MessageDigest) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException)

Example 43 with OAuthSystemException

use of org.apache.amber.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 44 with OAuthSystemException

use of org.apache.amber.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 45 with OAuthSystemException

use of org.apache.amber.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)

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