Search in sources :

Example 21 with OAuthSystemException

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

the class OAuthOkHttpClient method execute.

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(mediaType, request.getBody()) : 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 : Builder(okhttp3.Request.Builder) OAuthClientResponse(org.apache.oltu.oauth2.client.response.OAuthClientResponse) Response(okhttp3.Response) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) Request(okhttp3.Request) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) MediaType(okhttp3.MediaType) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Example 22 with OAuthSystemException

use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project irida by phac-nml.

the class RemoteAPITokenServiceImpl method updateTokenFromRefreshToken.

/**
 * {@inheritDoc}
 */
@Transactional
public RemoteAPIToken updateTokenFromRefreshToken(RemoteAPI api) {
    RemoteAPIToken token = null;
    try {
        token = getToken(api);
        String refreshToken = token.getRefreshToken();
        if (refreshToken != null) {
            URI serviceTokenLocation = UriBuilder.fromUri(api.getServiceURI()).path("oauth").path("token").build();
            OAuthClientRequest tokenRequest = OAuthClientRequest.tokenLocation(serviceTokenLocation.toString()).setClientId(api.getClientId()).setClientSecret(api.getClientSecret()).setRefreshToken(refreshToken).setGrantType(GrantType.REFRESH_TOKEN).buildBodyMessage();
            OAuthJSONAccessTokenResponse accessToken = oauthClient.accessToken(tokenRequest);
            token = buildTokenFromResponse(accessToken, api);
            delete(api);
            token = create(token);
            logger.debug("Token for api " + api + " updated by refresh token.");
        } else {
            logger.debug("No refresh token for api " + api + ". Cannot update access token.");
        }
    } catch (EntityNotFoundException ex) {
        logger.debug("Token not found for api " + api + ".  Cannot update access token.");
    } catch (OAuthProblemException | OAuthSystemException ex) {
        logger.error("Updating token by refresh token failed", ex.getMessage());
    }
    return token;
}
Also used : OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) RemoteAPIToken(ca.corefacility.bioinformatics.irida.model.RemoteAPIToken) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) EntityNotFoundException(ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) URI(java.net.URI) Transactional(org.springframework.transaction.annotation.Transactional)

Example 23 with OAuthSystemException

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

the class StructrOAuthClient method getEndUserAuthorizationRequestUri.

/**
 * Create an end-user authorization request
 *
 * Use with {@literal response.setRedirect(request.getLocationUri());}
 *
 * @param request
 * @return request URI
 */
public String getEndUserAuthorizationRequestUri(final HttpServletRequest request) {
    OAuthClientRequest oauthClientRequest;
    try {
        oauthClientRequest = OAuthClientRequest.authorizationLocation(authorizationLocation).setClientId(clientId).setRedirectURI(getAbsoluteUrl(request, redirectUri)).setScope(getScope()).setResponseType(getResponseType()).setState(getState()).buildQueryMessage();
        logger.info("Authorization request location URI: {}", oauthClientRequest.getLocationUri());
        return oauthClientRequest.getLocationUri();
    } catch (OAuthSystemException ex) {
        logger.error("", ex);
    }
    return null;
}
Also used : OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest)

Example 24 with OAuthSystemException

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

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) IOException(java.io.IOException) ApiException(com.vcita.platform.client.ApiException) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException)

Example 25 with OAuthSystemException

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

the class Callback method getSaneProviderUserInfo.

/**
 * Get user info for services which are sane enough to have an identity resource
 * that serves json
 * with <code>id</code>, <code>email</code> and <code>name</code> keys.
 * @param provider Who to ask.
 * @param accessToken An access token.
 * @return The delegated identity.
 * @throws OAuthSystemException
 * @throws OAuthProblemException
 * @throws JSONException If things aren't so sane after all.
 */
private DelegatedIdentity getSaneProviderUserInfo(String provider, String accessToken) throws OAuthSystemException, OAuthProblemException, JSONException {
    Properties props = InterMineContext.getWebProperties();
    String prefix = "oauth2." + provider;
    String identityEndpoint = props.getProperty(prefix + ".identity-resource");
    String envelopeKey = props.getProperty(prefix + ".identity-envelope");
    String idKey = props.getProperty(prefix + ".id-key", "id");
    String nameKey = props.getProperty(prefix + ".name-key", "name");
    String emailKey = props.getProperty(prefix + ".email-key", "email");
    String authMechanism = props.getProperty(prefix + ".resource-auth-mechanism", "queryparam");
    OAuthBearerClientRequest requestBuilder = new OAuthBearerClientRequest(identityEndpoint).setAccessToken(accessToken);
    OAuthClientRequest bearerClientRequest;
    if ("queryparam".equals(authMechanism)) {
        bearerClientRequest = requestBuilder.buildQueryMessage();
    } else if ("header".equals(authMechanism)) {
        bearerClientRequest = requestBuilder.buildHeaderMessage();
    } else if ("body".equals(authMechanism)) {
        bearerClientRequest = requestBuilder.buildBodyMessage();
    } else {
        throw new OAuthSystemException("Unknown authorisation mechanism: " + authMechanism);
    }
    LOG.debug("Requesting identity information:" + " URI = " + bearerClientRequest.getLocationUri() + " HEADERS = " + bearerClientRequest.getHeaders() + " BODY = " + bearerClientRequest.getBody());
    bearerClientRequest.setHeader("Accept", "application/json");
    OAuthClient oauthClient = new OAuthClient(new URLConnectionClient());
    OAuthResourceResponse resp = oauthClient.resource(bearerClientRequest, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
    return parseIdentity(provider, envelopeKey, idKey, nameKey, emailKey, resp.getBody());
}
Also used : OAuthBearerClientRequest(org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest) URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) OAuthResourceResponse(org.apache.oltu.oauth2.client.response.OAuthResourceResponse) OAuthClient(org.apache.oltu.oauth2.client.OAuthClient) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) Properties(java.util.Properties) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest)

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