oauth.signpost.exception.OAuthException Java Examples

The following examples show how to use oauth.signpost.exception.OAuthException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IMSPOXRequest.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public static HttpPost buildReplaceResult(String url, String key, String secret, String sourcedid, String score, String resultData, Boolean isUrl) throws IOException, OAuthException, GeneralSecurityException {
	String dataXml = "";
	if (resultData != null) {
		String format = isUrl ? resultDataUrl : resultDataText;
		dataXml = String.format(format, StringEscapeUtils.escapeXml(resultData));
	}
	//*LAMS* the following line was added by LAMS and also messageIdentifier was added to the line after it
	String messageIdentifier = UUID.randomUUID().toString();
	String xml = String.format(replaceResultMessage, messageIdentifier, StringEscapeUtils.escapeXml(sourcedid),
			StringEscapeUtils.escapeXml(score), dataXml);

	HttpParameters parameters = new HttpParameters();
	String hash = getBodyHash(xml);
	parameters.put("oauth_body_hash", URLEncoder.encode(hash, "UTF-8"));

	CommonsHttpOAuthConsumer signer = new CommonsHttpOAuthConsumer(key, secret);
	HttpPost request = new HttpPost(url);
	request.setHeader("Content-Type", "application/xml");
	request.setEntity(new StringEntity(xml, "UTF-8"));
	signer.setAdditionalParameters(parameters);
	signer.sign(request);
	return request;
}
 
Example #2
Source File: WithingsApiClient.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns a list of all measures in form {@link MeasureGroup} objects since
 * the given start time.
 * 
 * @param startTime
 *            time after which measures are returned
 * @return list of all measures
 * @throws OAuthException
 *             if an error occurs while signing the request
 * @throws WithingsConnectionException
 *             if a connection, server or authorization error occurs
 * @see http://www.withings.com/de/api#bodymetrics
 */
public List<MeasureGroup> getMeasures(int startTime) throws OAuthException, WithingsConnectionException {

    String url = getServiceUrl(API_ENDPOINT_MEASURE, API_METHOD_GET_MEASURES);
    if (startTime > 0) {
        url = url + "&startdate=" + startTime;
    }

    try {
        JsonObject jsonObject = call(consumer.sign(url));

        int status = jsonObject.get("status").getAsInt();

        if (status == 0) {
            JsonElement body = jsonObject.get("body");
            return gson.fromJson(body.getAsJsonObject(), MeasureResult.class).measureGroups;
        } else {
            throw new WithingsConnectionException("Withings API call failed: " + status);
        }

    } catch (Exception ex) {
        throw new WithingsConnectionException("Could not connect to URL: " + ex.getMessage(), ex);
    }
}
 
Example #3
Source File: BurpExtender.java    From burp-oauth with MIT License 6 votes vote down vote up
@Override
public void processHttpMessage(int toolFlag, boolean messageIsRequest, IHttpRequestResponse messageInfo)
{
	if (messageIsRequest && shouldSign(messageInfo))
	{
		HttpRequest req = new BurpHttpRequestWrapper(messageInfo);
		OAuthConsumer consumer = new DefaultOAuthConsumer(
				OAuthConfig.getConsumerKey(),
				OAuthConfig.getConsumerSecret());
		consumer.setTokenWithSecret(OAuthConfig.getToken(),
				OAuthConfig.getTokenSecret());
		try {
			consumer.sign(req);
		} catch (OAuthException oae) {
			oae.printStackTrace();
		}
	}
}
 
Example #4
Source File: WithingsAuthenticator.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Starts the OAuth authentication flow.
 */
public synchronized void startAuthentication(String accountId) {

    WithingsAccount withingsAccount = getAccount(accountId);
    if (withingsAccount == null) {
        logger.warn("Couldn't find Credentials of Account '{}'. Please check openhab.cfg or withings.cfg.",
                accountId);
        return;
    }

    OAuthConsumer consumer = withingsAccount.createConsumer();

    provider = new DefaultOAuthProvider(OAUTH_REQUEST_TOKEN_ENDPOINT, OAUTH_ACCESS_TOKEN_ENDPOINT_URL,
            OAUTH_AUTHORIZE_ENDPOINT_URL);

    try {
        String url = provider.retrieveRequestToken(consumer, this.redirectUrl);
        printSetupInstructions(url);
    } catch (OAuthException ex) {
        logger.error(ex.getMessage(), ex);
        printAuthenticationFailed(ex);
    }

}
 
Example #5
Source File: OAuthClient.java    From java-upwork with Apache License 2.0 5 votes vote down vote up
/**
 * Get authorization URL, use provided callback URL
 * 
    * @param   oauthCallback URL, i.e. oauth_callback
 * @return	URL for authorizing application
 * */
private String _getAuthorizationUrl(String oauthCallback) {
	String url = null;
       
	try {
           url = mOAuthProvider.retrieveRequestToken(mOAuthConsumer, oauthCallback);
       }
       catch (OAuthException e) {
           e.printStackTrace();
       }
	
	return url;
}
 
Example #6
Source File: OAuth.java    From restcommander with Apache License 2.0 5 votes vote down vote up
private Error(OAuthException exception) {
    this.exception = exception;
    if (this.exception instanceof OAuthMessageSignerException) {
        this.type = Type.MESSAGE_SIGNER;
    } else if (this.exception instanceof OAuthNotAuthorizedException) {
        this.type = Type.NOT_AUTHORIZED;
    } else if (this.exception instanceof OAuthExpectationFailedException) {
        this.type = Type.EXPECTATION_FAILED;
    } else if (this.exception instanceof OAuthCommunicationException) {
        this.type = Type.COMMUNICATION;
    } else {
        this.type = Type.OTHER;
    }
    this.details = exception.getMessage();
}
 
Example #7
Source File: OAuth.java    From restcommander with Apache License 2.0 5 votes vote down vote up
/**
 * Exchange a request token for an access token.
 * @param token the token obtained from a previous call
 * @param secret your application secret
 * @return a Response object holding either the result in case of a success or the error
 */
public Response retrieveAccessToken(String token, String secret) {
     OAuthConsumer consumer = new DefaultOAuthConsumer(info.consumerKey, info.consumerSecret);
    consumer.setTokenWithSecret(token, secret);
    String verifier = Params.current().get("oauth_verifier");
    try {
        provider.retrieveAccessToken(consumer, verifier);
    } catch (OAuthException e) {
        return Response.error(new Error(e));
    }
    return Response.success(consumer.getToken(), consumer.getTokenSecret());
}
 
Example #8
Source File: OAuth.java    From restcommander with Apache License 2.0 5 votes vote down vote up
/**
 * Request the request token and secret.
 * @param callbackURL the URL where the provider should redirect to
 * @return a Response object holding either the result in case of a success or the error
 */
public Response retrieveRequestToken(String callbackURL) {
    OAuthConsumer consumer = new DefaultOAuthConsumer(info.consumerKey, info.consumerSecret);
    try {
        provider.retrieveRequestToken(consumer, callbackURL);
    } catch (OAuthException e) {
        return Response.error(new Error(e));
    }
    return Response.success(consumer.getToken(), consumer.getTokenSecret());
}
 
Example #9
Source File: IMSPOXRequest.java    From basiclti-util-java with Apache License 2.0 5 votes vote down vote up
public static HttpPost buildReplaceResult(String url, String key, String secret, String sourcedid,
	String score, String resultData, Boolean isUrl, String messageId) throws IOException, OAuthException, GeneralSecurityException
{
	String dataXml = "";
	if (resultData != null) {
		String format = isUrl ? resultDataUrl : resultDataText;
		dataXml = String.format(format, StringEscapeUtils.escapeXml(resultData));
	}

	String messageIdentifier = StringUtils.isBlank(messageId) ? String.valueOf(new Date().getTime()) : messageId;
	String xml = String.format(ReplaceResultMessageTemplate,
		StringEscapeUtils.escapeXml(messageIdentifier),
		StringEscapeUtils.escapeXml(sourcedid),
		StringEscapeUtils.escapeXml(score),
		dataXml);

	HttpParameters parameters = new HttpParameters();
	String hash = getBodyHash(xml);
	parameters.put("oauth_body_hash", URLEncoder.encode(hash, "UTF-8"));

	CommonsHttpOAuthConsumer signer = new CommonsHttpOAuthConsumer(key, secret);
	HttpPost request = new HttpPost(url);
	request.setHeader("Content-Type", "application/xml");
	request.setEntity(new StringEntity(xml, "UTF-8"));
	signer.setAdditionalParameters(parameters);
	signer.sign(request);
	return request;
}
 
Example #10
Source File: IMSPOXRequest.java    From basiclti-util-java with Apache License 2.0 5 votes vote down vote up
public static void sendReplaceResult(String url, String key, String secret, String sourcedid, String score, String resultData, Boolean isUrl) throws IOException, OAuthException, GeneralSecurityException {
	HttpPost request = buildReplaceResult(url, key, secret, sourcedid, score, resultData, isUrl);
	DefaultHttpClient client = new DefaultHttpClient();
	HttpResponse response = client.execute(request);
	if (response.getStatusLine().getStatusCode() >= 400) {
		throw new HttpResponseException(response.getStatusLine().getStatusCode(),
				response.getStatusLine().getReasonPhrase());
	}
}
 
Example #11
Source File: WithingsAuthenticator.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Finishes the OAuth authentication flow.
 * 
 * @param verificationCode
 *            OAuth verification code
 * @param userId
 *            user id
 */
public synchronized void finishAuthentication(String accountId, String verificationCode, String userId) {

    WithingsAccount withingsAccount = getAccount(accountId);
    if (withingsAccount == null) {
        logger.warn("Couldn't find Credentials of Account '{}'. Please check openhab.cfg or withings.cfg.",
                accountId);
        return;
    }

    OAuthConsumer consumer = withingsAccount.consumer;

    if (provider == null || consumer == null) {
        logger.warn("Could not finish authentication. Please execute 'startAuthentication' first.");
        return;
    }

    try {
        provider.retrieveAccessToken(consumer, verificationCode);
    } catch (OAuthException ex) {
        logger.error(ex.getMessage(), ex);
        printAuthenticationFailed(ex);
        return;
    }

    withingsAccount.userId = userId;
    withingsAccount.setOuathToken(consumer.getToken(), consumer.getTokenSecret());
    withingsAccount.registerAccount(componentContext.getBundleContext());
    withingsAccount.persist();

    printAuthenticationSuccessful();
}
 
Example #12
Source File: SigningInterceptor.java    From Woodmin with Apache License 2.0 5 votes vote down vote up
@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    try {
        HttpRequest httpRequest = consumer.sign(request);
        Request authenticateRequest = (Request) httpRequest.unwrap();
        return chain.proceed(authenticateRequest);
    } catch (OAuthException e) {
        Log.e(LOG_TAG, "Error " + e.getMessage());
        throw new IOException("Could not sign request", e);
    }
}
 
Example #13
Source File: OAuthClient.java    From java-upwork with Apache License 2.0 5 votes vote down vote up
/**
 * Get access token-secret pair
 * 
 * @param	verifier OAuth verifier, which was got after authorization 
 * @return	Access token-secret pair
 * */
public HashMap<String, String> getAccessTokenSet(String verifier) {
	try {
           mOAuthProvider.retrieveAccessToken(mOAuthConsumer, verifier);
       }
       catch (OAuthException e) {
           e.printStackTrace();
       }
	
	return setTokenWithSecret(mOAuthConsumer.getToken(), mOAuthConsumer.getTokenSecret()); 
}
 
Example #14
Source File: SigningInterceptor.java    From Woodmin with Apache License 2.0 5 votes vote down vote up
@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    try {
        HttpRequest httpRequest = consumer.sign(request);
        Request authenticateRequest = (Request) httpRequest.unwrap();
        return chain.proceed(authenticateRequest);
    } catch (OAuthException e) {
        Log.e(LOG_TAG, "Error " + e.getMessage());
        throw new IOException("Could not sign request", e);
    }
}
 
Example #15
Source File: OsmConnection.java    From osmapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
private HttpURLConnection sendRequest(
		String call, String method, boolean authenticate, ApiRequestWriter writer)
		throws IOException, OAuthException
{
	HttpURLConnection connection = openConnection(call);
	if(method != null)
	{
		connection.setRequestMethod(method);
	}

	if(writer != null && writer.getContentType() != null)
	{
		connection.setRequestProperty("Content-Type", writer.getContentType());
		connection.setRequestProperty("charset", CHARSET.toLowerCase(Locale.UK));
	}

	if(authenticate)
	{
		createOAuthConsumer().sign(connection);
	}

	if(writer != null)
	{
		sendRequestPayload(connection, writer);
	}

	return connection;
}
 
Example #16
Source File: OAuthSigningInterceptor.java    From Forage with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public Response intercept(Chain chain) throws IOException {
    Request original = chain.request();


    if (original.header(ApiConstants.OAUTH_ENABLE_HEADER) != null) {
        try {
            original = (Request) consumer.sign(original).unwrap();
        } catch (OAuthException e) {
            throw new IOException("Could not sign request", e);
        }
    }
    return chain.proceed(original);
}
 
Example #17
Source File: OAuthWebViewDialogFragment.java    From AndroidApp with Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected List<String> doInBackground() throws OAuthException {
    provider.retrieveAccessToken(consumer, verificationCode);
    // must use an own connection here and not the normal singleton because since the
    // authorization process is not finished, the new authorized consumer is not applied yet
    OsmConnection osm = new OsmConnection(OSM_API_URL, ApplicationConstants.USER_AGENT, consumer);

    return new PermissionsDao(osm).get();
}
 
Example #18
Source File: IMSPOXRequest.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static void sendReplaceResult(String url, String key, String secret, String sourcedid, String score, String resultData, Boolean isUrl) throws IOException, OAuthException, GeneralSecurityException {
	HttpPost request = buildReplaceResult(url, key, secret, sourcedid, score, resultData, isUrl);
	//*LAMS* replaced DefaultHttpClient with HttpClient
	HttpClient client = HttpClients.custom()
	        .setDefaultRequestConfig(RequestConfig.custom()
	            .setCookieSpec(CookieSpecs.STANDARD).build())
	        .build(); // DefaultHttpClient client = new DefaultHttpClient();
	HttpResponse response = client.execute(request);
	if (response.getStatusLine().getStatusCode() >= 400) {
		throw new HttpResponseException(response.getStatusLine().getStatusCode(),
				response.getStatusLine().getReasonPhrase());
	}
}
 
Example #19
Source File: SigningInterceptor.java    From okhttp-signpost with Apache License 2.0 5 votes vote down vote up
@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    try {
        return chain.proceed((Request) consumer.sign(request).unwrap());
    } catch (OAuthException e) {
        throw new IOException("Could not sign request", e);
    }
}
 
Example #20
Source File: WithingsAuthenticator.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
private void printAuthenticationFailed(OAuthException ex) {
    logger.info(LINE);
    logger.info("# Withings authentication FAILED: " + ex.getMessage());
    logger.info("# Try to restart authentication by executing 'withings:startAuthentication'");
    logger.info(LINE);
}
 
Example #21
Source File: IMSPOXRequest.java    From basiclti-util-java with Apache License 2.0 4 votes vote down vote up
public static void sendReplaceResult(String url, String key, String secret, String sourcedid, String score, String resultData) throws IOException, OAuthException, GeneralSecurityException {
	sendReplaceResult(url, key, secret, sourcedid, score, resultData, false);
}
 
Example #22
Source File: IMSPOXRequest.java    From basiclti-util-java with Apache License 2.0 4 votes vote down vote up
public static HttpPost buildReplaceResult(String url, String key, String secret, String sourcedid, String score, String resultData, Boolean isUrl) throws IOException, OAuthException, GeneralSecurityException {
	return buildReplaceResult(url, key, secret, sourcedid, score, resultData, isUrl, null);
}
 
Example #23
Source File: IMSPOXRequest.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public static void sendReplaceResult(String url, String key, String secret, String sourcedid, String score) throws IOException, OAuthException, GeneralSecurityException {
	sendReplaceResult(url, key, secret, sourcedid, score, null);
}
 
Example #24
Source File: IMSPOXRequest.java    From basiclti-util-java with Apache License 2.0 4 votes vote down vote up
public static void sendReplaceResult(String url, String key, String secret, String sourcedid, String score) throws IOException, OAuthException, GeneralSecurityException {
	sendReplaceResult(url, key, secret, sourcedid, score, null);
}
 
Example #25
Source File: OAuthClient.java    From java-upwork with Apache License 2.0 4 votes vote down vote up
/**
 * Send signed POST OAuth request
 * 
 * @param	url Relative URL
 * @param	type Type of HTTP request (HTTP method)
 * @param	params Hash of parameters
 * @throws	JSONException If JSON object is invalid or request was abnormal
 * @return	{@link JSONObject} JSON Object that contains data from response
 * */
private JSONObject sendPostRequest(String url, Integer type, HashMap<String, String> params) throws JSONException {
	String fullUrl = getFullUrl(url);
	HttpPost request = new HttpPost(fullUrl);
	
	switch(type) {
	case METHOD_PUT:
	case METHOD_DELETE:
		// assign overload value
       	String oValue;
       	if (type == METHOD_PUT) {
       		oValue = "put";
       	} else {
       		oValue = "delete";
       	}
       	params.put(OVERLOAD_PARAM, oValue);
	case METHOD_POST:
		break;
	default:
           throw new RuntimeException("Wrong http method requested");
	}
	
	// doing post request using json to avoid issue with urlencoded symbols
	JSONObject json = new JSONObject();
	
       for (Map.Entry<String, String> entry : params.entrySet()) {
           json.put(entry.getKey(), entry.getValue());
       }
	
	request.setHeader("Content-Type", "application/json");
	try {
		request.setEntity(new StringEntity(json.toString()));
	} catch (UnsupportedEncodingException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	
       // sign request
	try {
		mOAuthConsumer.sign(request);
	}
	catch (OAuthException e) {
           e.printStackTrace();
       }
	
       return UpworkRestClient.getJSONObject(request, type, params);
   }
 
Example #26
Source File: OAuthWebViewDialogFragment.java    From AndroidApp with Mozilla Public License 2.0 4 votes vote down vote up
@Override
protected String doInBackground() throws OAuthException {
    return provider.retrieveRequestToken(consumer, CALLBACK_URL);
}
 
Example #27
Source File: IMSPOXRequest.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public static void sendReplaceResult(String url, String key, String secret, String sourcedid, String score, String resultData) throws IOException, OAuthException, GeneralSecurityException {
	sendReplaceResult(url, key, secret, sourcedid, score, resultData, false);
}
 
Example #28
Source File: WithingsApiClient.java    From openhab1-addons with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Returns a list of all measures in form {@link MeasureGroup} objects.
 * 
 * @return list of all measures
 * @throws OAuthException
 *             if an error occurs while signing the request
 * @throws WithingsConnectionException
 *             if a connection, server or authorization error occurs
 * @see http://www.withings.com/de/api#bodymetrics
 */
public List<MeasureGroup> getMeasures() throws OAuthException, WithingsConnectionException {
    return getMeasures(0);
}