oauth.signpost.OAuthConsumer Java Examples

The following examples show how to use oauth.signpost.OAuthConsumer. 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: 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 #2
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 #3
Source File: OsmConnection.java    From osmapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
private OAuthConsumer createOAuthConsumer() throws OAuthExpectationFailedException
{
	synchronized(oauthLock)
	{
		if(oauth == null)
		{
			throw new OAuthExpectationFailedException(
					"This class has been initialized without a OAuthConsumer. Only API calls " +
					"that do not require authentication can be made.");
		}

		// "clone" the original consumer every time because the consumer is documented to be not
		// thread safe and maybe multiple threads are making calls to this class
		OAuthConsumer consumer = new DefaultOAuthConsumer(
				oauth.getConsumerKey(), oauth.getConsumerSecret());
		consumer.setTokenWithSecret(oauth.getToken(), oauth.getTokenSecret());
		return consumer;
	}
}
 
Example #4
Source File: KAAPIAdapter.java    From android-viewer-for-khan-academy with GNU General Public License v3.0 5 votes vote down vote up
public void fetchUserVideos(final OAuthConsumer consumer, final EntityCallback<List<UserVideo>> callback) {
	String url = "http://www.khanacademy.org/api/v1/user/videos";
	new KAEntityCollectionFetcherTask<UserVideo>(UserVideo.class, url, consumer) {
		@Override
		protected void onPostExecute(List<UserVideo> result) {
			if (result == null) {
				exception.printStackTrace();
				// But don't crash.
			}
			callback.call(result);
		}
	}.execute();
}
 
Example #5
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 #6
Source File: OAuthTest.java    From burp-oauth with MIT License 5 votes vote down vote up
@Test
public void testSignature() throws Exception {
	HttpRequest hr = reqWrapForTestInput(1);
	OAuthConsumer consumer = new DefaultOAuthConsumer("1234", "5678");
	consumer.setTokenWithSecret("9ABC", "DEF0");
	consumer.sign(hr);
}
 
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: WSUrlFetch.java    From restcommander with Apache License 2.0 5 votes vote down vote up
private HttpURLConnection prepare(URL url, String method) {
    if (this.username != null && this.password != null && this.scheme != null) {
        String authString = null;
        switch (this.scheme) {
        case BASIC: authString = basicAuthHeader(); break;
        default: throw new RuntimeException("Scheme " + this.scheme + " not supported by the UrlFetch WS backend.");
        }
        this.headers.put("Authorization", authString);
    }
    try {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(this.followRedirects);
        connection.setReadTimeout(this.timeout * 1000);
        for (String key: this.headers.keySet()) {
            connection.setRequestProperty(key, headers.get(key));
        }
        checkFileBody(connection);
        if (this.oauthToken != null && this.oauthSecret != null) {
            OAuthConsumer consumer = new DefaultOAuthConsumer(oauthInfo.consumerKey, oauthInfo.consumerSecret);
            consumer.setTokenWithSecret(oauthToken, oauthSecret);
            consumer.sign(connection);
        }
        return connection;
    } catch(Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #10
Source File: OAuth1Utils.java    From shimmer with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an oauth consumer used for signing request URLs.
 *
 * @return The OAuthConsumer.
 */
public static OAuthConsumer createOAuthConsumer(String clientId, String clientSecret) {
    OAuthConsumer consumer =
        new DefaultOAuthConsumer(clientId, clientSecret);
    consumer.setSigningStrategy(new QueryStringSigningStrategy());
    return consumer;
}
 
Example #11
Source File: RestTask.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
@Override
protected RestResult doInBackground(String... args) {
    try {
        request = createRequest();
        if (isCancelled())
            throw new InterruptedException();
        OAuthConsumer consumer = Session.getInstance().getOAuthConsumer();
        if (consumer != null) {
            AccessToken accessToken = Session.getInstance().getAccessToken();
            if (accessToken != null) {
                consumer.setTokenWithSecret(accessToken.getKey(), accessToken.getSecret());
            }
            consumer.sign(request);
        }
        request.setHeader("Accept-Language", Locale.getDefault().getLanguage());
        request.setHeader("API-Client", String.format("uservoice-android-%s", UserVoice.getVersion()));
        AndroidHttpClient client = AndroidHttpClient.newInstance(String.format("uservoice-android-%s", UserVoice.getVersion()), Session.getInstance().getContext());
        if (isCancelled())
            throw new InterruptedException();
        // TODO it would be nice to find a way to abort the request on cancellation
        HttpResponse response = client.execute(request);
        if (isCancelled())
            throw new InterruptedException();
        HttpEntity responseEntity = response.getEntity();
        StatusLine responseStatus = response.getStatusLine();
        int statusCode = responseStatus != null ? responseStatus.getStatusCode() : 0;
        String body = responseEntity != null ? EntityUtils.toString(responseEntity) : null;
        client.close();
        if (isCancelled())
            throw new InterruptedException();
        return new RestResult(statusCode, new JSONObject(body));
    } catch (Exception e) {
        return new RestResult(e);
    }
}
 
Example #12
Source File: Session.java    From uservoice-android-sdk with MIT License 5 votes vote down vote up
public OAuthConsumer getOAuthConsumer(Context context) {
    if (oauthConsumer == null) {
        if (getConfig(context).getKey() != null)
            oauthConsumer = new OkOAuthConsumer(getConfig(context).getKey(), getConfig(context).getSecret());
        else if (clientConfig != null)
            oauthConsumer = new OkOAuthConsumer(clientConfig.getKey(), clientConfig.getSecret());
    }
    return oauthConsumer;
}
 
Example #13
Source File: ConnectionTestFactory.java    From osmapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static OAuthConsumer createConsumerThatAllowsEverything()
{
	OAuthConsumer result = new DefaultOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
	result.setTokenWithSecret(
			"2C4LiOQBOn96kXHyal7uzMJiqpCsiyDBvb8pomyX",
			"1bFMIQpgmu5yjywt3kknopQpcRmwJ6snDDGF7kdr");
	return result;
}
 
Example #14
Source File: ConnectionTestFactory.java    From osmapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static OAuthConsumer createConsumerThatProhibitsEverything()
{
	OAuthConsumer result = new DefaultOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
	result.setTokenWithSecret(
			"RCamNf4TT7uNeFjmigvOUWhajp5ERFZmcN1qvi7a",
			"72dzmAvuNBEOVKkif3JSYdzMlAq2dw5OnIG75dtX");
	return result;
}
 
Example #15
Source File: ConnectionTestFactory.java    From osmapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static OsmConnection createConnection(User user)
{
	OAuthConsumer consumer = null;

	if(user == User.ALLOW_EVERYTHING)
		consumer = createConsumerThatAllowsEverything();
	else if(user == User.ALLOW_NOTHING)
		consumer = createConsumerThatProhibitsEverything();
	else if(user == User.UNKNOWN)
		consumer = createUnknownUser();

	return new OsmConnection(TEST_API_URL, USER_AGENT, consumer);
}
 
Example #16
Source File: OsmConnection.java    From osmapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
public OAuthConsumer getOAuth()
{
	synchronized(oauthLock)
	{
		return oauth;
	}
}
 
Example #17
Source File: OsmConnection.java    From osmapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void setOAuth(OAuthConsumer oauth)
{
	synchronized(oauthLock)
	{
		this.oauth = oauth;
	}
}
 
Example #18
Source File: RestTask.java    From uservoice-android-sdk with MIT License 5 votes vote down vote up
@Override
protected RestResult doInBackground(String... args) {
    try {
        Request request = createRequest();
        if (isCancelled())
            throw new InterruptedException();
        OkHttpClient client = new OkHttpClient();
        OAuthConsumer consumer = Session.getInstance().getOAuthConsumer(context);
        if (consumer != null) {
            AccessToken accessToken = Session.getInstance().getAccessToken();
            if (accessToken != null) {
                consumer.setTokenWithSecret(accessToken.getKey(), accessToken.getSecret());
            }
            request = (Request) consumer.sign(request).unwrap();
        }
        Log.d("UV", urlPath);
        if (isCancelled())
            throw new InterruptedException();
        // TODO it would be nice to find a way to abort the request on cancellation
        Response response = client.newCall(request).execute();
        if (isCancelled())
            throw new InterruptedException();
        int statusCode = response.code();
        String body = response.body().string();
        if (statusCode >= 400) {
            Log.d("UV", body);
        }
        if (isCancelled())
            throw new InterruptedException();
        return new RestResult(statusCode, new JSONObject(body));
    } catch (Exception e) {
        return new RestResult(e);
    }
}
 
Example #19
Source File: Authenticator.java    From AndroidApp with Mozilla Public License 2.0 5 votes vote down vote up
public static OAuthConsumer createOAuthConsumer(OAuthConsumer oauth) throws OAuthExpectationFailedException {
    if (oauth == null) {
        throw new OAuthExpectationFailedException(
                "This class has been initialized without a OAuthConsumer. Only API calls " +
                        "that do not require authentication can be made.");
    }

    // "clone" the original consumer every time because the consumer is documented to be not
    // thread safe and maybe multiple threads are making calls to this class
    OAuthConsumer consumer = new DefaultOAuthConsumer(
            oauth.getConsumerKey(), oauth.getConsumerSecret());
    consumer.setTokenWithSecret(oauth.getToken(), oauth.getTokenSecret());
    return consumer;
}
 
Example #20
Source File: OAuthWebViewDialogFragment.java    From AndroidApp with Mozilla Public License 2.0 5 votes vote down vote up
public static OAuthWebViewDialogFragment create(@NonNull OAuthConsumer consumer,
                                                @NonNull OAuthProvider provider) {
    OAuthWebViewDialogFragment f = new OAuthWebViewDialogFragment();

    Bundle args = new Bundle();
    args.putSerializable(CONSUMER, consumer);
    args.putSerializable(PROVIDER, provider);
    f.setArguments(args);

    return f;
}
 
Example #21
Source File: KAAPIAdapter.java    From android-viewer-for-khan-academy with GNU General Public License v3.0 5 votes vote down vote up
public OAuthConsumer getConsumer(User user) {
	OAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
	if (user != null) {
		String token = user.getToken();
		String secret = user.getSecret();
		if (token != null && secret != null) {
			consumer.setTokenWithSecret(token, secret);
		}
	}
	return consumer;
}
 
Example #22
Source File: OAuthComponent.java    From AndroidApp with Mozilla Public License 2.0 5 votes vote down vote up
private void onAuthorizationSuccess(OAuthConsumer consumer) {
    OAuth.saveConsumer(prefs, consumer);
    // the osm connection is a singleton. Updating its oauth consumer will provide the new consumer
    // for all daos out there (using this connection)
    osmConnection.setOAuth(OAuth.loadConsumer(prefs));

    new PostAuthorizationTask().execute();
}
 
Example #23
Source File: OAuthComponent.java    From AndroidApp with Mozilla Public License 2.0 5 votes vote down vote up
public void onOAuthAuthorized(OAuthConsumer consumer, List<String> permissions) {
    if (permissions.containsAll(OAuth.REQUIRED_PERMISSIONS)) {
        onAuthorizationSuccess(consumer);
    } else {
        Toast.makeText(context, R.string.oauth_failed_permissions, Toast.LENGTH_LONG).show();
        onAuthorizationFailed();
    }
}
 
Example #24
Source File: KAAPIAdapter.java    From android-viewer-for-khan-academy with GNU General Public License v3.0 5 votes vote down vote up
public void login(final String token, final String secret, final UserLoginHandler handler) {
	OAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
	consumer.setTokenWithSecret(token, secret);
	fetchUser(consumer, new EntityCallback<User>() {
		@Override
		public void call(User returnedUser) {
			
			if (returnedUser != null) {
				returnedUser.setToken(token);
				returnedUser.setSecret(secret);
				try {
					Dao<User, String> userDao = dataService.getHelper().getUserDao();
					if (userDao.getConnectionSource().isOpen()) {
						userDao.createOrUpdate(returnedUser);
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			handler.onUserLogin(returnedUser);
			currentUser = returnedUser;
			setCurrentUser(returnedUser);
			doUserUpdate(returnedUser);
		}
	});
}
 
Example #25
Source File: OAuth.java    From AndroidApp with Mozilla Public License 2.0 5 votes vote down vote up
public static OAuthConsumer loadConsumer(SharedPreferences prefs) {
    OAuthConsumer result = createConsumer();
    String accessToken = prefs.getString(Prefs.OAUTH_ACCESS_TOKEN, null);
    String accessTokenSecret = prefs.getString(Prefs.OAUTH_ACCESS_TOKEN_SECRET, null);
    result.setTokenWithSecret(accessToken, accessTokenSecret);
    return result;
}
 
Example #26
Source File: KAAPIAdapter.java    From android-viewer-for-khan-academy with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Fetch data for the currently logged-in user. Requires prior authentication.
 * 
 * @param callback
 */
public void fetchUser(final OAuthConsumer consumer, final EntityCallback<User> callback) {
	String url = "http://www.khanacademy.org/api/v1/user";
	new KAEntityFetcherTask<User>(url, consumer) {
		@Override
		protected void onPostExecute(User result) {
			callback.call(result);
		}
	}.execute();
}
 
Example #27
Source File: KAEntityFetcherTask.java    From android-viewer-for-khan-academy with GNU General Public License v3.0 4 votes vote down vote up
public KAEntityFetcherTask(String url, OAuthConsumer consumer) {
	this(url);
	this.consumer = consumer;
}
 
Example #28
Source File: SpringRequestFactory.java    From android-viewer-for-khan-academy with GNU General Public License v3.0 4 votes vote down vote up
public SpringRequestFactory(OAuthConsumer consumer) {
	this.consumer = consumer;
}
 
Example #29
Source File: KAEntityCollectionFetcherTask.java    From android-viewer-for-khan-academy with GNU General Public License v3.0 4 votes vote down vote up
public KAEntityCollectionFetcherTask(Class<T> type, String url, OAuthConsumer consumer) {
	this(type, url);
	this.consumer = consumer;
}
 
Example #30
Source File: ConnectionTestFactory.java    From osmapi with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static OAuthConsumer createUnknownUser()
{
	return new DefaultOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
}