Esempio n. 1
0
 /**
  * Add some of the parameters needed to request access to a protected resource, if they aren't
  * already in the message.
  *
  * @throws IOException
  * @throws URISyntaxException
  */
 public void addRequiredParameters(OAuthAccessor accessor)
     throws OAuthException, IOException, URISyntaxException {
   final Map<String, String> pMap = OAuth.newMap(parameters);
   if (pMap.get(OAuth.OAUTH_TOKEN) == null && accessor.accessToken != null) {
     addParameter(OAuth.OAUTH_TOKEN, accessor.accessToken);
   }
   final OAuthConsumer consumer = accessor.consumer;
   if (pMap.get(OAuth.OAUTH_CONSUMER_KEY) == null) {
     addParameter(OAuth.OAUTH_CONSUMER_KEY, consumer.consumerKey);
   }
   String signatureMethod = pMap.get(OAuth.OAUTH_SIGNATURE_METHOD);
   if (signatureMethod == null) {
     signatureMethod = (String) consumer.getProperty(OAuth.OAUTH_SIGNATURE_METHOD);
     if (signatureMethod == null) {
       signatureMethod = OAuth.HMAC_SHA1;
     }
     addParameter(OAuth.OAUTH_SIGNATURE_METHOD, signatureMethod);
   }
   if (pMap.get(OAuth.OAUTH_TIMESTAMP) == null) {
     addParameter(OAuth.OAUTH_TIMESTAMP, (System.currentTimeMillis() / 1000) + "");
   }
   if (pMap.get(OAuth.OAUTH_NONCE) == null) {
     addParameter(OAuth.OAUTH_NONCE, System.nanoTime() + "");
   }
   if (pMap.get(OAuth.OAUTH_VERSION) == null) {
     addParameter(OAuth.OAUTH_VERSION, OAuth.VERSION_1_0);
   }
   if (pMap.get(OAuth.OAUTH_BODY_HASH) == null && bodyAsStream != null) {
     addParameter(OAuth.OAUTH_BODY_HASH, getBodyHash());
   }
   this.sign(accessor);
 }
  public String retrieveRequestToken(OAuthConsumer consumer, String callbackUrl)
      throws OAuthMessageSignerException, OAuthNotAuthorizedException,
          OAuthExpectationFailedException, OAuthCommunicationException {

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

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

    String callbackConfirmed = this.responseParameters.getFirst(OAuth.OAUTH_CALLBACK_CONFIRMED);
    this.responseParameters.remove(OAuth.OAUTH_CALLBACK_CONFIRMED);
    this.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 (this.isOAuth10a) {
      return OAuth.addQueryParameters(
          this.authorizationWebsiteUrl, OAuth.OAUTH_TOKEN, consumer.getToken());
    } else {
      return OAuth.addQueryParameters(
          this.authorizationWebsiteUrl,
          OAuth.OAUTH_TOKEN,
          consumer.getToken(),
          OAuth.OAUTH_CALLBACK,
          callbackUrl);
    }
  }
 protected OAuthConsumer newConsumer(String name) throws MalformedURLException {
   String base = consumerProperties.getProperty(name + ".serviceProvider.baseURL");
   URL baseURL = (base == null) ? null : new URL(base);
   OAuthServiceProvider serviceProvider =
       new OAuthServiceProvider(
           getURL(baseURL, name + ".serviceProvider.requestTokenURL"),
           getURL(baseURL, name + ".serviceProvider.userAuthorizationURL"),
           getURL(baseURL, name + ".serviceProvider.accessTokenURL"));
   OAuthConsumer consumer =
       new OAuthConsumer(
           consumerProperties.getProperty(name + ".callbackURL"),
           consumerProperties.getProperty(name + ".consumerKey"),
           consumerProperties.getProperty(name + ".consumerSecret"),
           serviceProvider);
   consumer.setProperty("name", name);
   if (baseURL != null) {
     consumer.setProperty("serviceProvider.baseURL", baseURL);
   }
   for (Map.Entry prop : consumerProperties.entrySet()) {
     String propName = (String) prop.getKey();
     if (propName.startsWith(name + ".consumer.")) {
       String c = propName.substring(name.length() + 10);
       consumer.setProperty(c, prop.getValue());
     }
   }
   return consumer;
 }
  @Test
  public void shouldSignHttpRequestMessage() throws Exception {

    OAuthConsumer consumer =
        new DefaultOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET, SignatureMethod.HMAC_SHA1);

    consumer.setTokenWithSecret(TOKEN, TOKEN_SECRET);

    consumer.sign(request);

    Header authHeader = request.getFirstHeader("Authorization");
    assertNotNull(authHeader);

    String oauthHeader = authHeader.getValue();
    assertTrue(oauthHeader.startsWith("OAuth "));

    HashMap<String, String> params = oauthHeaderToParamsMap(oauthHeader);
    assertNotNull(params.get("oauth_consumer_key"));
    assertNotNull(params.get("oauth_token"));
    assertNotNull(params.get("oauth_signature_method"));
    assertNotNull(params.get("oauth_signature"));
    assertNotNull(params.get("oauth_timestamp"));
    assertNotNull(params.get("oauth_nonce"));
    assertNotNull(params.get("oauth_version"));
  }
 @Test(expected = OAuthExpectationFailedException.class)
 public void shouldThrowIfConsumerSecretNotSet() throws Exception {
   OAuthConsumer consumer =
       new DefaultOAuthConsumer(CONSUMER_KEY, null, SignatureMethod.HMAC_SHA1);
   consumer.setTokenWithSecret(TOKEN, TOKEN_SECRET);
   consumer.sign(request);
 }
  public void retrieveAccessToken(OAuthConsumer consumer, String oauthVerifier)
      throws OAuthMessageSignerException, OAuthNotAuthorizedException,
          OAuthExpectationFailedException, OAuthCommunicationException {

    if (consumer.getToken() == null || consumer.getTokenSecret() == null) {
      throw new OAuthExpectationFailedException(
          "Authorized request token or token secret not set. "
              + "Did you retrieve an authorized request token before?");
    }

    if (this.isOAuth10a && oauthVerifier != null) {
      retrieveToken(consumer, this.accessTokenEndpointUrl, OAuth.OAUTH_VERIFIER, oauthVerifier);
    } else {
      retrieveToken(consumer, this.accessTokenEndpointUrl);
    }
  }
  @Test
  public void shouldPercentEncodeOAuthParameters() throws Exception {
    OAuthConsumer consumer =
        new DefaultOAuthConsumer("1%2", CONSUMER_SECRET, SignatureMethod.HMAC_SHA1);
    consumer.setTokenWithSecret("3 4", TOKEN_SECRET);

    consumer.sign(request);

    Header authHeader = request.getFirstHeader("Authorization");
    assertNotNull(authHeader);

    String oauthHeader = authHeader.getValue();

    HashMap<String, String> params = oauthHeaderToParamsMap(oauthHeader);
    assertEquals("\"1%252\"", params.get("oauth_consumer_key"));
    assertEquals("\"3%204\"", params.get("oauth_token"));
  }
  /**
   * Implemented by subclasses. The responsibility of this method is to contact the service provider
   * at the given endpoint URL and fetch a request or access token. What kind of token is retrieved
   * solely depends on the URL being used.
   *
   * <p>Correct implementations of this method must guarantee the following post-conditions:
   *
   * <ul>
   *   <li>the {@link OAuthConsumer} passed to this method must have a valid {@link
   *       OAuth#OAUTH_TOKEN} and {@link OAuth#OAUTH_TOKEN_SECRET} set by calling {@link
   *       OAuthConsumer#setTokenWithSecret(String, String)}
   *   <li>{@link #getResponseParameters()} must return the set of query parameters served by the
   *       service provider in the token response, with all OAuth specific parameters being removed
   * </ul>
   *
   * @param consumer the {@link OAuthConsumer} that should be used to sign the request
   * @param endpointUrl the URL at which the service provider serves the OAuth token that is to be
   *     fetched
   * @param additionalParameters you can pass parameters here (typically OAuth parameters such as
   *     oauth_callback or oauth_verifier) which will go directly into the signer, i.e. you don't
   *     have to put them into the request first, just so the consumer pull them out again. Pass
   *     them sequentially in key/value order.
   * @throws OAuthMessageSignerException if signing the token request fails
   * @throws OAuthCommunicationException if a network communication error occurs
   * @throws OAuthNotAuthorizedException if the server replies 401 - Unauthorized
   * @throws OAuthExpectationFailedException if an expectation has failed, e.g. because the server
   *     didn't reply in the expected format
   */
  protected void retrieveToken(
      OAuthConsumer consumer, String endpointUrl, String... additionalParameters)
      throws OAuthMessageSignerException, OAuthCommunicationException, OAuthNotAuthorizedException,
          OAuthExpectationFailedException {
    Map<String, String> defaultHeaders = getRequestHeaders();

    if (consumer.getConsumerKey() == null || consumer.getConsumerSecret() == null) {
      throw new OAuthExpectationFailedException("Consumer key or secret not set");
    }

    HttpRequest request = null;
    HttpResponse response = null;
    try {
      request = createRequest(endpointUrl);
      for (String header : defaultHeaders.keySet()) {
        request.setHeader(header, defaultHeaders.get(header));
      }
      if (additionalParameters != null) {
        HttpParameters httpParams = new HttpParameters();
        httpParams.putAll(additionalParameters, true);
        consumer.setAdditionalParameters(httpParams);
      }

      if (this.listener != null) {
        this.listener.prepareRequest(request);
      }

      consumer.sign(request);

      if (this.listener != null) {
        this.listener.prepareSubmission(request);
      }

      response = sendRequest(request);
      int statusCode = response.getStatusCode();

      boolean requestHandled = false;
      if (this.listener != null) {
        requestHandled = this.listener.onResponseReceived(request, response);
      }
      if (requestHandled) {
        return;
      }

      if (statusCode >= 300) {
        handleUnexpectedResponse(statusCode, response);
      }

      HttpParameters responseParams = OAuth.decodeForm(response.getContent());

      String token = responseParams.getFirst(OAuth.OAUTH_TOKEN);
      String secret = responseParams.getFirst(OAuth.OAUTH_TOKEN_SECRET);
      responseParams.remove(OAuth.OAUTH_TOKEN);
      responseParams.remove(OAuth.OAUTH_TOKEN_SECRET);

      setResponseParameters(responseParams);

      if (token == null || secret == null) {
        throw new OAuthExpectationFailedException(
            "Request token or token secret not set in server reply. "
                + "The service provider you use is probably buggy.");
      }

      consumer.setTokenWithSecret(token, secret);

    } catch (OAuthNotAuthorizedException e) {
      throw e;
    } catch (OAuthExpectationFailedException e) {
      throw e;
    } catch (Exception e) {
      throw new OAuthCommunicationException(e);
    } finally {
      try {
        closeConnection(request, response);
      } catch (Exception e) {
        throw new OAuthCommunicationException(e);
      }
    }
  }