Search in sources :

Example 31 with OAuthSystemException

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

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

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

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

Example 35 with OAuthSystemException

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

the class Callback method getTokenResponse.

private OAuthAccessTokenResponse getTokenResponse(String redirect, OAuthAuthzResponse oar, OAuthProvider provider) throws OAuthSystemException, OAuthProblemException {
    OAuthClient oauthClient = new OAuthClient(new URLConnectionClient());
    OAuthClientRequest clientReq;
    TokenRequestBuilder requestBuilder = OAuthClientRequest.tokenLocation(provider.getTokenUrl()).setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(provider.getClientId()).setClientSecret(provider.getClientSecret()).setRedirectURI(redirect).setCode(oar.getCode());
    switch(provider.getMessageFormat()) {
        case BODY:
            clientReq = requestBuilder.buildBodyMessage();
            break;
        case QUERY:
            clientReq = requestBuilder.buildQueryMessage();
            break;
        default:
            throw new RuntimeException("Unknown message format");
    }
    LOG.info("Requesting access token: URI = " + clientReq.getLocationUri() + " BODY = " + clientReq.getBody());
    switch(provider.getResponseType()) {
        case FORM:
            return oauthClient.accessToken(clientReq, GitHubTokenResponse.class);
        case JSON:
            return oauthClient.accessToken(clientReq);
        default:
            throw new RuntimeException("Unknown response type");
    }
}
Also used : TokenRequestBuilder(org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder) URLConnectionClient(org.apache.oltu.oauth2.client.URLConnectionClient) OAuthClient(org.apache.oltu.oauth2.client.OAuthClient) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest)

Aggregations

OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)98 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)53 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)49 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)49 IOException (java.io.IOException)38 Request (okhttp3.Request)27 Response (okhttp3.Response)27 OAuthJSONAccessTokenResponse (org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse)21 URI (java.net.URI)17 Builder (okhttp3.Request.Builder)17 OAuthBearerClientRequest (org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest)16 Map (java.util.Map)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)13 MD5Generator (org.apache.oltu.oauth2.as.issuer.MD5Generator)12 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)12 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)12 Path (javax.ws.rs.Path)11