Search in sources :

Example 96 with OAuthSystemException

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

the class AbstractAuthorizationGrantHandler method updateCacheIfEnabled.

private void updateCacheIfEnabled(AccessTokenDO newTokenBean, String scope, OauthTokenIssuer oauthTokenIssuer) throws IdentityOAuth2Exception {
    if (isHashDisabled && cacheEnabled) {
        AccessTokenDO tokenToCache = AccessTokenDO.clone(newTokenBean);
        // method is set as the token.
        if (oauthTokenIssuer.usePersistedAccessTokenAlias()) {
            try {
                String persistedTokenIdentifier = oauthTokenIssuer.getAccessTokenHash(newTokenBean.getAccessToken());
                tokenToCache.setAccessToken(persistedTokenIdentifier);
            } catch (OAuthSystemException e) {
                if (log.isDebugEnabled()) {
                    if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
                        log.debug("Token issuer: " + oauthTokenIssuer.getClass() + " was tried and" + " failed to parse the received token: " + tokenToCache.getAccessToken(), e);
                    } else {
                        log.debug("Token issuer: " + oauthTokenIssuer.getClass() + " was tried and" + " failed to parse the received token.", e);
                    }
                }
            }
        }
        String userId;
        try {
            userId = tokenToCache.getAuthzUser().getUserId();
        } catch (UserIdNotFoundException e) {
            throw new IdentityOAuth2Exception("User id is not available for user: " + tokenToCache.getAuthzUser().getLoggableUserId(), e);
        }
        String authenticatedIDP = OAuth2Util.getAuthenticatedIDP(tokenToCache.getAuthzUser());
        OAuthCacheKey cacheKey = getOAuthCacheKey(scope, tokenToCache.getConsumerKey(), userId, authenticatedIDP, getTokenBindingReference(tokenToCache));
        oauthCache.addToCache(cacheKey, tokenToCache);
        if (log.isDebugEnabled()) {
            log.debug("Access token was added to OAuthCache with cache key : " + cacheKey.getCacheKeyString());
        }
        // Adding AccessTokenDO to improve validation performance
        OAuth2Util.addTokenDOtoCache(newTokenBean);
    }
}
Also used : 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) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)

Example 97 with OAuthSystemException

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

the class TokenBindingExpiryEventHandler method handleEvent.

@Override
public void handleEvent(Event event) throws IdentityEventException {
    if (log.isDebugEnabled()) {
        log.debug(event.getEventName() + " event received to TokenBindingExpiryEventHandler.");
    }
    if (!IdentityEventConstants.EventName.SESSION_TERMINATE.name().equals(event.getEventName()) && !IdentityEventConstants.EventName.SESSION_EXPIRE.name().equals(event.getEventName())) {
        return;
    }
    HttpServletRequest request = getHttpRequestFromEvent(event);
    Map<String, Object> eventProperties = event.getEventProperties();
    AuthenticationContext context = (AuthenticationContext) eventProperties.get(IdentityEventConstants.EventProperty.CONTEXT);
    try {
        if (request == null) {
            if (log.isDebugEnabled()) {
                log.debug("HttpServletRequest object is null. Hence getting the session related information from " + "event and revoking the access tokens mapped to session");
            }
            revokeAccessTokensMappedForSessions(event);
            return;
        }
        if (FrameworkConstants.RequestType.CLAIM_TYPE_OIDC.equals(request.getParameter(TYPE))) {
            String consumerKey = context.getRelyingParty();
            String bindingType = null;
            if (StringUtils.isNotBlank(consumerKey)) {
                bindingType = OAuth2Util.getAppInformationByClientId(consumerKey).getTokenBindingType();
            }
            if (bindingType != null) {
                revokeTokensForBindingType(request, context.getLastAuthenticatedUser(), consumerKey, bindingType);
            }
            if (!OAuth2Constants.TokenBinderType.SSO_SESSION_BASED_TOKEN_BINDER.equals(bindingType)) {
                revokeTokensForCommonAuthCookie(request, context.getLastAuthenticatedUser());
            }
        } else {
            revokeTokensForCommonAuthCookie(request, context.getLastAuthenticatedUser());
        }
    } catch (IdentityOAuth2Exception | OAuthSystemException e) {
        log.error("Error while revoking the tokens on session termination.", e);
    } catch (InvalidOAuthClientException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error while revoking the tokens on session termination.", e);
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationContext(org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

Example 98 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project gobblin by apache.

the class SalesforceRestWriter method onConnect.

/**
 * Retrieve access token, if needed, retrieve instance url, and set server host URL
 * {@inheritDoc}
 * @see org.apache.gobblin.writer.http.HttpWriter#onConnect(org.apache.http.HttpHost)
 */
@Override
public void onConnect(URI serverHost) throws IOException {
    if (!StringUtils.isEmpty(accessToken)) {
        // No need to be called if accessToken is active.
        return;
    }
    try {
        getLog().info("Getting Oauth2 access token.");
        OAuthClientRequest request = OAuthClientRequest.tokenLocation(serverHost.toString()).setGrantType(GrantType.PASSWORD).setClientId(clientId).setClientSecret(clientSecret).setUsername(userId).setPassword(password + securityToken).buildQueryMessage();
        OAuthClient client = new OAuthClient(new URLConnectionClient());
        OAuthJSONAccessTokenResponse response = client.accessToken(request, OAuth.HttpMethod.POST);
        accessToken = response.getAccessToken();
        setCurServerHost(new URI(response.getParam("instance_url")));
    } catch (OAuthProblemException e) {
        throw new NonTransientException("Error while authenticating with Oauth2", e);
    } catch (OAuthSystemException e) {
        throw new RuntimeException("Failed getting access token", e);
    } catch (URISyntaxException e) {
        throw new RuntimeException("Failed due to invalid instance url", e);
    }
}
Also used : OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) NonTransientException(org.apache.gobblin.exception.NonTransientException) URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) OAuthClient(org.apache.oltu.oauth2.client.OAuthClient) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) URISyntaxException(java.net.URISyntaxException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) URI(java.net.URI)

Example 99 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project fattureincloud-java-sdk by fattureincloud.

the class OAuthOkHttpClient method execute.

@Override
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers, String requestMethod, Class<T> responseClass) throws OAuthSystemException, OAuthProblemException {
    MediaType mediaType = MediaType.parse("application/json");
    Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());
    if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            if (entry.getKey().equalsIgnoreCase("Content-Type")) {
                mediaType = MediaType.parse(entry.getValue());
            } else {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }
    RequestBody body = request.getBody() != null ? RequestBody.create(request.getBody(), mediaType) : null;
    requestBuilder.method(requestMethod, body);
    try {
        Response response = client.newCall(requestBuilder.build()).execute();
        return OAuthClientResponseFactory.createCustomResponse(response.body().string(), response.body().contentType().toString(), response.code(), responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
Also used : OAuthClientResponse(org.apache.oltu.oauth2.client.response.OAuthClientResponse) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) IOException(java.io.IOException)

Example 100 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project fattureincloud-java-sdk by fattureincloud.

the class RetryingOAuth method retryingIntercept.

private Response retryingIntercept(Chain chain, boolean updateTokenAndRetryOnAuthorizationFailure) throws IOException {
    Request request = chain.request();
    // If the request already has an authorization (e.g. Basic auth), proceed with the request as is
    if (request.header("Authorization") != null) {
        return chain.proceed(request);
    }
    // Get the token if it has not yet been acquired
    if (getAccessToken() == null) {
        updateAccessToken(null);
    }
    OAuthClientRequest oAuthRequest;
    if (getAccessToken() != null) {
        // Build the request
        Request.Builder requestBuilder = request.newBuilder();
        String requestAccessToken = getAccessToken();
        try {
            oAuthRequest = new OAuthBearerClientRequest(request.url().toString()).setAccessToken(requestAccessToken).buildHeaderMessage();
        } catch (OAuthSystemException e) {
            throw new IOException(e);
        }
        Map<String, String> headers = oAuthRequest.getHeaders();
        for (String headerName : headers.keySet()) {
            requestBuilder.addHeader(headerName, headers.get(headerName));
        }
        requestBuilder.url(oAuthRequest.getLocationUri());
        // Execute the request
        Response response = chain.proceed(requestBuilder.build());
        // 401/403 response codes most likely indicate an expired access token, unless it happens two times in a row
        if (response != null && (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED || response.code() == HttpURLConnection.HTTP_FORBIDDEN) && updateTokenAndRetryOnAuthorizationFailure) {
            try {
                if (updateAccessToken(requestAccessToken)) {
                    response.body().close();
                    return retryingIntercept(chain, false);
                }
            } catch (Exception e) {
                response.body().close();
                throw e;
            }
        }
        return response;
    } else {
        return chain.proceed(chain.request());
    }
}
Also used : OAuthBearerClientRequest(org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) Response(okhttp3.Response) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) Request(okhttp3.Request) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) OAuthBearerClientRequest(org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest) IOException(java.io.IOException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) ApiException(it.fattureincloud.sdk.ApiException) IOException(java.io.IOException) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException)

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