DropBox oauth_signature生成

时间:2012-05-24 10:01:09

标签: java oauth dropbox-api

String baseString="POST&";
String subBaseString = "oauth_consumer_key="+oauth_consumer_key+"&oauth_nonce="+nonce+"&oauth_signature_method="+oauth_signature_method;
subBaseString += "&oauth_timestamp="+  oauth_timestamp+"&oauth_token="+oauth_token+"&oauth_version=1.0";
baseString += URLEncoder.encode(baseRequest, "UTF-8");
baseString += "&" +  URLEncoder.encode(subBaseString, "UTF-8");

String result;
try {

    SecretKeySpec signingKey = new SecretKeySpec(oauth_consumer_key.getBytes(), oauth_signature_method);

    Mac mac = Mac.getInstance(oauth_signature_method);
    mac.init(signingKey);

    byte[] rawHmac = mac.doFinal(baseString.getBytes());

    // base64-encode the hmac
    result = Base64.encode(rawHmac);

} catch (Exception e) {
    throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}

这是我的oauth_signature代码....

但是收到错误..

  

{“error”:“API v1 +中的OAuthError。请求错误签名:签名无效或丢失”}

1 个答案:

答案 0 :(得分:2)

OAuth签名,随机数和时间戳是您使用普通HTTP时所必需的所有安全措施。但由于Dropbox API可以通过HTTPS使用,因此您可以放弃所有这些复杂性,只需使用PLAINTEXT signature mode就更简单了。

这是完成这项工作的一些示例Java代码。 (它将OAuth信息放在“授权”HTTP标头中,但如果需要,可以改为URL参数。)

 /**
  * @param token
  *    For all "real" API endpoints, pass in the access token here.
  *    For "/oauth/access_token", pass in the request token here.
  *    (For "/oauth/request_token", use {@link #buildInitialOAuthHeader}.)
  */
 public static HttpHeader buildOAuthHeader(AppInfo appInfo, Token token)
 {
     StringBuilder buf = new StringBuilder();
     buf.append("OAuth ");
     buf.append("oauth_token=\"").append(token.key).append("\"");
     buf.append(", oauth_consumer_key=\"").append(appInfo.key).append("\"");
     buf.append(", oauth_signature_method=\"PLAINTEXT\"");
     buf.append(", oauth_signature=\"").append(appInfo.secret).append("&").append(token.secret).append("\"");
     return new HttpHeader("Authorization", buf.toString());
 }

 /**
  * For "/oauth/request_token".
  */
 public static HttpHeader buildInitialOAuthHeader(AppInfo appInfo)
 {
     StringBuilder buf = new StringBuilder();
     buf.append("OAuth ");
     buf.append(" oauth_consumer_key=\"").append(appInfo.key).append("\"");
     buf.append(", oauth_signature_method=\"PLAINTEXT\"");
     buf.append(", oauth_signature=\"").append(appInfo.secret).append("&\"");
     return new HttpHeader("Authorization", buf.toString());
 }