Search in sources :

Example 1 with OAuthClientRequest

use of org.apache.amber.oauth2.client.request.OAuthClientRequest in project incubator-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 2 with OAuthClientRequest

use of org.apache.amber.oauth2.client.request.OAuthClientRequest in project android-client by GenesisVision.

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 : 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 3 with OAuthClientRequest

use of org.apache.amber.oauth2.client.request.OAuthClientRequest in project airavata by apache.

the class AuthResponse method authenticate.

public static AuthResponse authenticate(String username, String password) throws AuthenticationException {
    try {
        OAuthClientRequest request = OAuthClientRequest.tokenLocation(hostName + "/oauth2/token").setClientId(clientId).setClientSecret(clientSecret).setGrantType(GrantType.PASSWORD).setRedirectURI("").setUsername(username).setPassword(password).setScope("openid").buildBodyMessage();
        URLConnectionClient ucc = new URLConnectionClient();
        org.apache.oltu.oauth2.client.OAuthClient oAuthClient = new org.apache.oltu.oauth2.client.OAuthClient(ucc);
        OAuthResourceResponse resp = oAuthClient.resource(request, OAuth.HttpMethod.POST, OAuthResourceResponse.class);
        // converting JSON to object
        ObjectMapper mapper = new ObjectMapper();
        AuthResponse authResponse;
        try {
            authResponse = mapper.readValue(resp.getBody(), AuthResponse.class);
        } catch (Exception e) {
            return null;
        }
        String accessToken = authResponse.getAccess_token();
        if (accessToken != null && !accessToken.isEmpty()) {
            request = new OAuthBearerClientRequest(hostName + "/oauth2/userinfo?schema=openid").buildQueryMessage();
            ucc = new URLConnectionClient();
            request.setHeader("Authorization", "Bearer " + accessToken);
            oAuthClient = new org.apache.oltu.oauth2.client.OAuthClient(ucc);
            resp = oAuthClient.resource(request, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
            Map<String, String> profile = mapper.readValue(resp.getBody(), Map.class);
            return authResponse;
        }
    } catch (Exception ex) {
        throw new AuthenticationException(ex.getMessage());
    }
    return null;
}
Also used : OAuthResourceResponse(org.apache.oltu.oauth2.client.response.OAuthResourceResponse) DefaultOAuthClient(org.apache.airavata.service.security.oauth.DefaultOAuthClient) AuthenticationException(org.apache.airavata.model.error.AuthenticationException) AuthenticationException(org.apache.airavata.model.error.AuthenticationException) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException) OAuthBearerClientRequest(org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest) URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) ObjectMapper(org.codehaus.jackson.map.ObjectMapper)

Example 4 with OAuthClientRequest

use of org.apache.amber.oauth2.client.request.OAuthClientRequest in project mbed-cloud-sdk-java by ARMmbed.

the class OAuth method retryingIntercept.

private Response retryingIntercept(Chain chain, boolean updateTokenAndRetryOnAuthorizationFailure) throws IOException {
    Request request = chain.request();
    // If the request already have an authorization (eg. Basic auth), do nothing
    if (request.header("Authorization") != null) {
        return chain.proceed(request);
    }
    // If first time, get the token
    OAuthClientRequest oAuthRequest;
    if (getAccessToken() == null) {
        updateAccessToken(null);
    }
    if (getAccessToken() != null) {
        // Build the request
        Builder rb = request.newBuilder();
        String requestAccessToken = new String(getAccessToken());
        try {
            oAuthRequest = new OAuthBearerClientRequest(request.url().toString()).setAccessToken(requestAccessToken).buildHeaderMessage();
        } catch (OAuthSystemException e) {
            throw new IOException(e);
        }
        for (Map.Entry<String, String> header : oAuthRequest.getHeaders().entrySet()) {
            rb.addHeader(header.getKey(), header.getValue());
        }
        rb.url(oAuthRequest.getLocationUri());
        // Execute the request
        Response response = chain.proceed(rb.build());
        // 401/403 most likely indicates that access token has expired. Unless it happens two times in a row.
        if (response != null && (response.code() == HTTP_UNAUTHORIZED || response.code() == HTTP_FORBIDDEN) && updateTokenAndRetryOnAuthorizationFailure) {
            if (updateAccessToken(requestAccessToken)) {
                return retryingIntercept(chain, false);
            }
        }
        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) AuthenticationRequestBuilder(org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder) Builder(okhttp3.Request.Builder) TokenRequestBuilder(org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder) 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) Map(java.util.Map)

Example 5 with OAuthClientRequest

use of org.apache.amber.oauth2.client.request.OAuthClientRequest 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)

Aggregations

OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)36 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)24 IOException (java.io.IOException)21 Request (okhttp3.Request)18 Response (okhttp3.Response)18 Builder (okhttp3.Request.Builder)17 OAuthJSONAccessTokenResponse (org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse)13 OAuthBearerClientRequest (org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest)11 AuthenticationRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder)10 TokenRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder)10 Map (java.util.Map)9 MediaType (okhttp3.MediaType)9 RequestBody (okhttp3.RequestBody)9 OAuthClientResponse (org.apache.oltu.oauth2.client.response.OAuthClientResponse)9 URI (java.net.URI)6 URLConnectionClient (org.apache.oltu.oauth2.client.URLConnectionClient)6 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)5 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)5 OAuthRegistrationClient (org.apache.oltu.oauth2.ext.dynamicreg.client.OAuthRegistrationClient)3 OAuthClientRegistrationResponse (org.apache.oltu.oauth2.ext.dynamicreg.client.response.OAuthClientRegistrationResponse)3