Search in sources :

Example 26 with OAuthSystemException

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

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException 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 28 with OAuthSystemException

use of org.apache.oltu.oauth2.common.exception.OAuthSystemException 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 29 with OAuthSystemException

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

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

the class RemoteAPITokenServiceImpl method createTokenFromAuthCode.

/**
 * Get a new token from the given auth code
 * @param authcode      the auth code to create a token for
 * @param remoteAPI     the remote api to get a token for
 * @param tokenRedirect a redirect url to get the token from
 * @return a new token
 * @throws OAuthSystemException If building the token request fails
 * @throws OAuthProblemException If the token request fails
 */
@Transactional
public RemoteAPIToken createTokenFromAuthCode(String authcode, RemoteAPI remoteAPI, String tokenRedirect) throws OAuthSystemException, OAuthProblemException {
    String serviceURI = remoteAPI.getServiceURI();
    // Build the token location for this service
    URI serviceTokenLocation = UriBuilder.fromUri(serviceURI).path("oauth").path("token").build();
    logger.debug("Remote token location: " + serviceTokenLocation);
    // Create the token request form the given auth code
    OAuthClientRequest tokenRequest = OAuthClientRequest.tokenLocation(serviceTokenLocation.toString()).setClientId(remoteAPI.getClientId()).setClientSecret(remoteAPI.getClientSecret()).setRedirectURI(tokenRedirect).setCode(authcode).setGrantType(GrantType.AUTHORIZATION_CODE).buildBodyMessage();
    // execute the request
    OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(tokenRequest);
    // read the response for the access token
    String accessToken = accessTokenResponse.getAccessToken();
    // Handle Refresh Tokens
    String refreshToken = accessTokenResponse.getRefreshToken();
    // check the token expiry
    Long expiresIn = accessTokenResponse.getExpiresIn();
    Long currentTime = System.currentTimeMillis();
    Date expiry = new Date(currentTime + (expiresIn * ONE_SECOND_IN_MS));
    logger.debug("Token expiry: " + expiry);
    // create the OAuth2 token and store it
    RemoteAPIToken token = new RemoteAPIToken(accessToken, refreshToken, remoteAPI, expiry);
    return create(token);
}
Also used : RemoteAPIToken(ca.corefacility.bioinformatics.irida.model.RemoteAPIToken) OAuthJSONAccessTokenResponse(org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) URI(java.net.URI) Date(java.util.Date) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)57 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)50 IOException (java.io.IOException)37 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)32 Request (okhttp3.Request)27 Response (okhttp3.Response)27 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)27 OAuthJSONAccessTokenResponse (org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse)21 Builder (okhttp3.Request.Builder)17 OAuthBearerClientRequest (org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest)16 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 Map (java.util.Map)12 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)12 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)12 URI (java.net.URI)11 URLConnectionClient (org.apache.oltu.oauth2.client.URLConnectionClient)10 AuthenticationRequestBuilder (org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder)10