java - 使用 OAuth-Signpost 和 Apache HttpComponents 签署 POST 请求的正确方法是什么?

标签 java oauth http-post apache-httpcomponents signpost

我目前正在使用 OAuth-Signpost Java 库对从客户端发送到实现 OAuth 身份验证的服务器的请求进行签名。发出 GET 请求(使用 HttpURLConnection)时一切正常:请求已签名,包含参数并且签名在目标中匹配。但是,它似乎不适用于 POST 请求。我知道使用 HttpURLConnection 签署 POST 时可能会出现的问题,因此我转移到 Apache HttpComponents 库来处理这些请求。我在以下示例中发送的参数是纯字符串和类似 XML 的字符串 ('rxml')。我的代码如下:

public Response exampleMethod(String user, String sp, String ep, String rn, String rxml){

   //All these variables are proved to be correct (they work right in GET requests)
    String uri = "...";
    String consumerKey = "...";
    String consumerSecret = "...";
    String token = "...";
    String secret = "...";

  //create the parameters list
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("user", user));
    params.add(new BasicNameValuePair("sp", sp));
    params.add(new BasicNameValuePair("ep", ep));
    params.add(new BasicNameValuePair("rn", rn));
    params.add(new BasicNameValuePair("rxml", rxml));

   // create a consumer object and configure it with the access
   // token and token secret obtained from the service provider
    OAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
    consumer.setTokenWithSecret(token, secret);

   // create an HTTP request to a protected resource
    HttpPost request = new HttpPost(uri);

   // sign the request      
    consumer.sign(request);       

   // set the parameters into the request
    request.setEntity(new UrlEncodedFormEntity(params));

   // send the request
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(request);

   //if request was unsuccessful
    if(response.getStatusLine().getStatusCode()!=200){
        return Response.status(response.getStatusLine().getStatusCode()).build();
    }

   //if successful, return the response body
    HttpEntity resEntity = response.getEntity();
    String responseBody = "";

    if (resEntity != null) {
        responseBody = EntityUtils.toString(resEntity);
    }

    EntityUtils.consume(resEntity);

    httpClient.getConnectionManager().shutdown();

    return Response.status(200).entity(responseBody).build();

}

当我向服务器发送 POST 请求时,我收到一条错误消息,提示签名(我发送的签名和服务器自行计算的签名)不匹配,所以我猜这与基本字符串有关他们正在签名以及 POST 签名的工作方式,因为他们在双方处理相同的 key 和 secret (选中)。

我读到过一种方法是将参数设置为 URL 的一部分(如在 GET 请求中)。但它对我不起作用,因为 XML 参数可能会超过 URL 长度,因此需要将其作为 POST 参数发送。

我想我在签署 POST 请求或处理参数时做错了什么,但我不知道它是什么。拜托,你能帮帮我吗?

P.S:如果我缺少有关此问题的上下文、错误跟踪或其他信息,我深表歉意,但我是这里的新手。因此,如果您需要更多信息,请随时向我询问。

最佳答案

一些背景故事/解释

过去几天我一直遇到类似的问题,几乎要放弃了。直到我听说我公司负责提供与我通信的服务的人员已将他们配置为从查询字符串而不是 header 参数中读取 OAuth 信息。

因此,当您将它传递给请求进行签名时,而不是从 Signpost 放入请求的 header 参数 Authorization 中读取它,例如 [Authorization: OAuth oauth_consumer_key="USER", oauth_nonce="4027096421883800497", oauth_signature="Vd%2BJEb0KnUhEv1E1g3nf4Vl3SSM%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1363100774", oauth_version="1.0"] ,尝试读取查询字符串的服务,例如 http://myservice.mycompany.com?oauth_consumer_key=USER&oauth_nonce=4027096421883800497&oauth_signature=Vd%2BJEb0KnUhEv1E1g3nf4Vl3SSM%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1363100774&oauth_version=1.0 .

问题在于,当我尝试对 url 进行签名,然后用它构建一个 HttpPost 请求时,该 url 得到了一个带有前缀 GET 而不是 POST 的基本字符串,它给出了另一个签名,然后是服务计算的签名。 Signpost 并没有做错任何事,它的 url 签名方法只是默认设置为 GET,没有其他开箱即用的可能性。之所以如此,是因为您应该在执行 POST 时读取 header 参数,而不是查询字符串(去鸡蛋我的那个“同事”的房子),并且 Signpost 在签署请求时添加这些参数,而您在执行 POST 时应该这样做。

signingbasestring可以在Signpost中生成的SigningBaseString类方法中观察到。

解决方案

现在我就是这样做的,但其他方式可能甚至更好。

  1. 获取路标源代码并将其添加到您的项目中。能拿到here
  2. 找到 OAuthConsumer类并更改签名方法,以便您可以传递请求应该是 POST 的信息。在我的例子中,我添加了一个像这样的 boolean 值 public String sign(String url, boolean POST)
  3. 现在您需要更改 sign AbstractOAuthConsumer 中的方法类,CommonsHttpOAuthConsumerDefaultOAuthConsumer延长。在我的例子中,我将 boolean 变量添加到方法和以下 if(POST) request.setMethod("POST");就在方法调用之前 sign(request);
  4. 现在请求是 Signpost 特定对象 HTTPRequest,因此这将引发错误。您需要更改它并添加方法 public void setMethod(String method); .
  5. 这将导致以下类出错HttpURLConnectionRequestAdapter , HttpRequestAdapterUrlStringRequestAdapter .您需要将方法实现添加到它们中,但风格不同。首先你要添加

    public void setMethod(String method){
    try {
     this.connection.setRequestMethod(method);
     } catch (ProtocolException e) {
    
        e.printStackTrace();
     }
    }
    

    第二次你会添加

    public void setMethod(String method){
    
       try {
           RequestWrapper wrapper = new RequestWrapper(this.request);
           wrapper.setMethod(method);
           request = wrapper;
       } catch (org.apache.http.ProtocolException e) {
        e.printStackTrace();
        }   
    }
    

    最后你要添加

    public void setMethod(String method){
       mMethod = method;
    }
    

    请注意,我只使用并尝试了第一个和最后一个。但这至少让你知道如何解决这个问题,如果你和我有同样的问题的话。

无论如何希望这对您有所帮助。

-德累斯顿先生

关于java - 使用 OAuth-Signpost 和 Apache HttpComponents 签署 POST 请求的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14601256/

相关文章:

java - 从字符串中获取字节

javascript - 通过 POST 将 JSON 字符串(数组)从 Javascript 发送到 PHP

android - 拆分 sqlite 文件以进行同步

java - java如何识别数组的末尾在哪里?

java - Libgdx:手机的后退按钮在屏幕之间继续

Facebook OAuth 错误 4 : API_EC_TOO_MANY_CALLS - Application request limit reached

oauth - 仅使用 OpenID 可以获得用户电子邮件吗?

java - 让多个线程对数据集进行操作,而一个线程将其汇总

java - 方法在不应该抛出 NumberFormatException 的地方抛出异常,到目前为止工作正常

javascript - 在 gmail 中使用 Nodejs 和 oauth