コード例 #1
0
  /**
   * This method takes into account the Indivo specificities when obtaining a request token, which
   * are detailed in this class description. It has the same signature as the standard
   * retrieveRequestToken() method except it takes an extra parameter recordId.
   *
   * @param consumer the OAuthConsumer to be used for OAuth processing
   * @param callbackUrl an optional alternative OAuth callback URL
   * @param recordId an optional record ID to be used when it is received by the start URL
   * @return the received request token as a String
   * @throws OAuthMessageSignerException
   * @throws OAuthNotAuthorizedException
   * @throws OAuthExpectationFailedException
   * @throws OAuthCommunicationException
   */
  public String retrieveRequestToken(OAuthConsumer consumer, String callbackUrl, RecordId recordId)
      throws OAuthMessageSignerException, OAuthNotAuthorizedException,
          OAuthExpectationFailedException, OAuthCommunicationException {

    // invalidate current credentials, if any
    consumer.setTokenWithSecret(null, null);

    // if a recordId is present, it has to be used only at request sending (another method in this
    // class) ...
    if (recordId != null) {
      // ... therefore we create a protected block to guarantee the shared recordId we set is not
      // overwritten
      synchronized (this) {
        // set the shared recordId to be used by method sendRequest()
        this.sharedRecordId = recordId;

        // 1.0a expects the callback to be sent while getting the request token.
        // 1.0 service providers would simply ignore this parameter.
        this.retrieveToken(
            consumer, super.getRequestTokenEndpointUrl(), OAuth.OAUTH_CALLBACK, callbackUrl);

        // unset the shared recordId
        this.sharedRecordId = null;
      }
    } else {
      this.retrieveToken(
          consumer, super.getRequestTokenEndpointUrl(), OAuth.OAUTH_CALLBACK, callbackUrl);
    }

    /// Indivo does not send OAUTH_CALLBACK_CONFIRMED for now
    /// this is why the following lines are commented
    /*
    String callbackConfirmed = super.getResponseParameters().getFirst(OAuth.OAUTH_CALLBACK_CONFIRMED);
    super.getResponseParameters().remove(OAuth.OAUTH_CALLBACK_CONFIRMED);
       isOAuth10a = Boolean.TRUE.toString().equals(callbackConfirmed);
    */

    // 1.0 service providers expect the callback as part of the auth URL,
    // Do not send when 1.0a.
    if (super.isOAuth10a()) {
      return OAuth.addQueryParameters(
          super.getAuthorizationWebsiteUrl(), OAuth.OAUTH_TOKEN, consumer.getToken());
    } else {
      return OAuth.addQueryParameters(
          super.getAuthorizationWebsiteUrl(),
          OAuth.OAUTH_TOKEN,
          consumer.getToken(),
          OAuth.OAUTH_CALLBACK,
          callbackUrl);
    }
  }
コード例 #2
0
ファイル: Tumblr.java プロジェクト: Ayonyx/tumblr-java
  private String[] getOAuthTokens()
      throws OAuthMessageSignerException, OAuthExpectationFailedException,
          OAuthCommunicationException, ClientProtocolException, IOException {

    /* basically, if we're getting here and these things are set we should have already set this information.
    if not, well then kaboom!!! don't mess up sammy! */
    if (oauth_callback != null && !oauth_callback.isEmpty()) {
      String[] result = new String[2];
      result[0] = consumer.getToken();
      result[1] = consumer.getTokenSecret();

      return result;
    }

    ArrayList<BasicNameValuePair> xauth_params = new ArrayList<BasicNameValuePair>();
    xauth_params.add(new BasicNameValuePair("x_auth_mode", "client_auth"));
    xauth_params.add(new BasicNameValuePair("x_auth_username", email));
    xauth_params.add(new BasicNameValuePair("x_auth_password", password));
    HttpPost post = new HttpPost("https://www.tumblr.com/oauth/access_token");
    try {
      UrlEncodedFormEntity entity = new UrlEncodedFormEntity(xauth_params);
      post.setEntity(entity);
      consumer.sign(post);
      HttpResponse response = client.execute(post);
      String s = convertToString(response.getEntity().getContent());
      String[] tokens = s.split("&");
      String[] result = new String[2];
      result[0] = tokens[0].split("=")[1];
      result[1] = tokens[1].split("=")[1];
      return result;
    } catch (UnsupportedEncodingException e) {
    }
    return null;
  }
    /**
     * Retrieve the oauth_verifier, and store the oauth and oauth_token_secret for future API calls.
     */
    @Override
    protected Void doInBackground(Uri... params) {
      final Uri uri = params[0];
      final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);

      try {
        provider.retrieveAccessToken(consumer, oauth_verifier);

        final Editor edit = prefs.edit();
        edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
        edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret());
        edit.commit();

        String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
        String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");

        consumer.setTokenWithSecret(token, secret);
        context.startActivity(new Intent(context, TwitterActivity.class));

        executeAfterAccessTokenRetrieval();

        Log.i(TAG, "OAuth - Access Token Retrieved");

      } catch (Exception e) {
        Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
      }

      return null;
    }
コード例 #4
0
  public static void main(String[] args) throws Exception {

    OAuthConsumer consumer =
        new DefaultOAuthConsumer(
            "iIlNngv1KdV6XzNYkoLA",
            "exQ94pBpLXFcyttvLoxU2nrktThrlsj580zjYzmoM",
            SignatureMethod.HMAC_SHA1);

    OAuthProvider provider =
        new DefaultOAuthProvider(
            consumer,
            "http://twitter.com/oauth/request_token",
            "http://twitter.com/oauth/access_token",
            "http://twitter.com/oauth/authorize");

    System.out.println("Fetching request token from Twitter...");

    // we do not support callbacks, thus pass OOB
    String authUrl = provider.retrieveRequestToken(OAuth.OUT_OF_BAND);

    System.out.println("Request token: " + consumer.getToken());
    System.out.println("Token secret: " + consumer.getTokenSecret());

    System.out.println("Now visit:\n" + authUrl + "\n... and grant this app authorization");
    System.out.println("Enter the PIN code and hit ENTER when you're done:");

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String pin = br.readLine();

    System.out.println("Fetching access token from Twitter...");

    provider.retrieveAccessToken(pin);

    System.out.println("Access token: " + consumer.getToken());
    System.out.println("Token secret: " + consumer.getTokenSecret());

    URL url = new URL("http://twitter.com/statuses/mentions.xml");
    HttpURLConnection request = (HttpURLConnection) url.openConnection();

    consumer.sign(request);

    System.out.println("Sending request to Twitter...");
    request.connect();

    System.out.println(
        "Response: " + request.getResponseCode() + " " + request.getResponseMessage());
  }
コード例 #5
0
 @Override
 public void onYozmAuthLoaded(YozmModel model, OAuthConsumer consumer) {
   // TODO Auto-generated method stub
   view.dismissLoading();
   AccessToken token = new AccessToken(consumer.getToken(), consumer.getTokenSecret());
   prefModel.setYozmAccessToken(token);
   yozmModel.loadYozmUserInfo(consumer);
 }
コード例 #6
0
 public PreferencesRegistry saveConsumer(OAuthConsumer consumer) {
   getEditor()
       .putString("consumer_key", consumer.getConsumerKey())
       .putString("consumer_secret", consumer.getConsumerSecret())
       .putString("token", consumer.getToken())
       .putString("token_secret", consumer.getTokenSecret())
       .commit();
   return this;
 }
コード例 #7
0
  public static void main(String[] args) throws Exception {

    OAuthConsumer consumer = new DefaultOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);

    OAuthProvider provider =
        new DefaultOAuthProvider(
            NETFLIX_REQUEST_TOKEN_URL, NETFLIX_ACCESS_TOKEN_URL, NETFLIX_AUTHORIZE_URL);

    System.out.println("Fetching request token from Netflix...");

    // we do not support callbacks, thus pass OOB
    String authUrl = provider.retrieveRequestToken(consumer, OAuth.OUT_OF_BAND);
    authUrl =
        OAuth.addQueryParameters(
            authUrl, OAuth.OAUTH_CONSUMER_KEY, CONSUMER_KEY, "application_name", APPLICATION_NAME);

    System.out.println("Request token: " + consumer.getToken());
    System.out.println("Token secret: " + consumer.getTokenSecret());

    System.out.println("Now visit:\n" + authUrl + "\n... and grant this app authorization");
    System.out.println("Enter the PIN code and hit ENTER when you're done:");

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String pin = br.readLine();

    System.out.println("Fetching access token from Twitter...");

    provider.retrieveAccessToken(consumer, pin);

    System.out.println("Access token: " + consumer.getToken());
    System.out.println("Token secret: " + consumer.getTokenSecret());

    URL url = new URL("http://api.netflix.com/catalog/titles");
    HttpURLConnection request = (HttpURLConnection) url.openConnection();

    consumer.sign(request);

    System.out.println("Sending request...");
    request.connect();

    System.out.println(
        "Response: " + request.getResponseCode() + " " + request.getResponseMessage());
  }
コード例 #8
0
  public static void test1()
      throws OAuthMessageSignerException, OAuthNotAuthorizedException,
          OAuthExpectationFailedException, OAuthCommunicationException, IOException {
    Properties prop = new Properties();
    InputStream in = KivaApiExampleWithSignPost.class.getResourceAsStream("/signpost.properties");
    prop.load(in);
    String consumerKey = prop.getProperty("oauth.consumer.key");
    String consumerSecret = prop.getProperty("oauth.consumer.secret");
    in.close();

    System.setProperty("debug", "true");

    OAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);

    // Note: we have to add the consumer key in the authorization URL to make it work
    OAuthProvider provider =
        new CommonsHttpOAuthProvider(
            REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, AUTHORIZATION_URL + "&client_id=" + consumerKey);
    /*
     *  This has to be done once to get request token
     */
    provider.setOAuth10a(true);
    // for some reason, SignPost does not append oauth_callback so I
    // added it directly into the AUTHORIZATION_URL
    String requestUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
    System.out.println("Copy/Paste the following URL in your browser: " + requestUrl);
    System.out.print("Enter your token: ");
    // read authorization code
    Scanner scanner = new Scanner(System.in);
    String authorizationCode = scanner.nextLine().trim();

    provider.retrieveAccessToken(consumer, authorizationCode);

    String accessToken = consumer.getToken();
    String tokenSecret = consumer.getTokenSecret();
    System.out.println("Token: " + accessToken + ". Secret: " + tokenSecret);

    // store token and secret somewhere in a database or in a file
    // so that it can be used later

    /*
     * To be done whenever you use the Kiva API
     */
    OAuthConsumer newConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
    newConsumer.setTokenWithSecret(accessToken, tokenSecret);
    HttpGet request = new HttpGet(RESOURCE_URL);
    consumer.sign(request);

    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(request);
    // send request and get content
    String content = IOUtil.toString(response.getEntity().getContent());
    System.out.println(content);
  }
コード例 #9
0
 public static void setLoginInformation(Context context, OAuthConsumer consumer) {
   getDefaultSharedPreferences(context)
       .edit()
       .putBoolean(context.getString(R.string.setting_account_loggedin_key), true)
       .commit();
   getSharedPreferences("oauth")
       .edit()
       .putString(
           context.getString(R.string.setting_oauth_consumer_key), consumer.getConsumerKey())
       .putString(
           context.getString(R.string.setting_oauth_consumer_secret), consumer.getConsumerSecret())
       .putString(context.getString(R.string.setting_oauth_token), consumer.getToken())
       .putString(
           context.getString(R.string.setting_oauth_token_secret), consumer.getTokenSecret())
       .commit();
 }
コード例 #10
0
  @RequestMapping(value = "/upgradeToken")
  public String upgradeToken(HttpServletRequest request, HttpServletResponse response)
      throws OAuthException, OAuthMessageSignerException, OAuthNotAuthorizedException,
          OAuthExpectationFailedException, OAuthCommunicationException {
    OAuthConsumer consumer =
        (OAuthConsumer) request.getSession().getAttribute(FRESHBOOKS_OAUTH_CONSUMER);
    OAuthProvider provider =
        (OAuthProvider) request.getSession().getAttribute(FRESHBOOKS_OAUTH_PROVIDER);
    String verifier = request.getParameter("oauth_verifier");
    provider.retrieveAccessToken(consumer, verifier);
    Guest guest = AuthHelper.getGuest();

    final Connector connector = Connector.getConnector("freshbooks");
    final ApiKey apiKey = guestService.createApiKey(guest.getId(), connector);

    guestService.setApiKeyAttribute(apiKey, "accessToken", consumer.getToken());
    guestService.setApiKeyAttribute(apiKey, "tokenSecret", consumer.getTokenSecret());

    return "redirect:/app/from/" + connector.getName();
  }
コード例 #11
0
ファイル: MeetupClient.java プロジェクト: snooplsm/Organizer
 public void saveSession(Editor edit) {
   edit.putString("oauthTokenSecret", consumer.getTokenSecret());
   edit.putString("oauthToken", consumer.getToken());
   edit.commit();
 }