【问题标题】:OAuth 1 Authorization Header with RestTemplate带有 RestTemplate 的 OAuth 1 授权标头
【发布时间】:2017-12-03 19:06:33
【问题描述】:

我正在尝试通过 OAuth 1 连接到 DropBox API。我有应用密钥和应用密码。我需要访问令牌和访问密钥。

我尝试使用 DropBox SDK,但找不到操作方法(当前教程解释了 OAuth 2)

我已经学习了本教程,它通过 cURL 工作:https://blogs.dropbox.com/developers/2012/07/using-oauth-1-0-with-the-plaintext-signature-method/

我无法通过 RestTemplate 使用该标头发出 POST 请求:

Authorization: OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT",
oauth_consumer_key="<app-key>", oauth_token="<request-token>",
oauth_signature="<app-secret>&<request-token-secret>"

我试过了:

RestTemplate restTemplate = new RestTemplateBuilder().build();

    HttpComponentsClientHttpRequestFactory rf =
            (HttpComponentsClientHttpRequestFactory) restTemplate.getRequestFactory();
    rf.setReadTimeout(1 * 1_000);
    rf.setConnectTimeout(1 * 1_000);

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization: ", "OAuth");
    headers.set("oauth_version", "1.0");
    headers.set("oauth_signature_method", "PLAINTEXT");
    headers.set("oauth_consumer_key", APP_KEY);
    headers.set("oauth_signature", APP_SECRET);

    HttpEntity<String> entity = new HttpEntity<>(headers);

    Object result = restTemplate.postForEntity(
            "https://api.dropbox.com/1/oauth/request_token",
            entity,
            Object.class)

它会导致 400 HTTP 错误请求错误。如何使用 RestTemplate 做到这一点?

【问题讨论】:

  • 你好@kamaci 你得到答案了吗?
  • 只是因为我碰巧落在了这个帖子上。在您的示例中,您没有遵循您链接的网站所说的内容。 Auth1 标头只是 1 个标头,而不是多个标头。因此,对于初学者,我建议尝试将这 5 个标头合并到 1 中。关键是“授权”,值是其余的称为授权字符串。 github.com/spring-projects/spring-social/blob/master/… 检查第 197 行。

标签: spring oauth resttemplate


【解决方案1】:

我已经为此工作了一段时间,直到我找到适合自己的解决方案。

 Object result = restClient.postData("https://api.dropbox.com/1/oauth/request_token",
            getHeaders(), entity, Object.class);

对于标题

private HttpHeaders getHeaders() throws UnsupportedEncodingException, NoSuchAlgorithmException,
        InvalidKeyException {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set(HttpHeaders.AUTHORIZATION, getAuthHeader());
    return headers;
}

private String getAuthHeader() throws UnsupportedEncodingException, NoSuchAlgorithmException,
        InvalidKeyException {
    String randomNumber = generateRandomString();
    String oauthNonce = getMd5(randomNumber);
    Long oauthTimestamp = Instant.now().getEpochSecond();
    String baseString = "POST&"+
            URLEncoder.encode( URL , StandardCharsets.UTF_8.toString()) + "&" +
            URLEncoder.encode(
                    ("deploy=" + DEPLOY +
                            + "&oauth_consumer_key=" + CONSUMER_KEY
                            + "&oauth_nonce=" + oauthNonce
                            + "&oauth_signature_method=" + "HMAC-SHA1"+
                            + "&oauth_timestamp=" + oauthTimestamp
                            + "&oauth_token=" + TOKEN
                            + "&oauth_version= 1.0"
                            + "&realm=" + REALM
                            + "&script=" + SCRIPT),StandardCharsets.UTF_8.toString()
            );
    String sigString = URLEncoder.encode(CONSUMER_SECRET,StandardCharsets.UTF_8.toString())
            + "&" + URLEncoder.encode(TOKEN_SECRET,StandardCharsets.UTF_8.toString());
    String signature= generateSignature(baseString,sigString,"HmacSHA1");
    String headers= " OAuth realm=\""+ URLEncoder.encode(
            REALM,StandardCharsets.UTF_8.toString()) + "\", "
            + "oauth_consumer_key=\"" + URLEncoder.encode(
                    CONSUMER_KEY,StandardCharsets.UTF_8.toString()) + "\", "
            + "oauth_token=\"" + URLEncoder.encode(TOKEN,StandardCharsets.UTF_8.toString()) + "\", "
            + "oauth_signature_method=\"" + URLEncoder.encode(
                    "HMAC-SHA1",StandardCharsets.UTF_8.toString()) + "\", "
            + "oauth_timestamp=\"" + URLEncoder.encode(
                    String.valueOf(oauthTimestamp).substring(0,10),StandardCharsets.UTF_8.toString()) + "\", "
            + "oauth_nonce=\"" + URLEncoder.encode(oauthNonce,StandardCharsets.UTF_8.toString()) + "\", "
            + "oauth_version=\"" + URLEncoder.encode(
                    "1.0",StandardCharsets.UTF_8.toString()) + "\", "
            + "oauth_signature=\"" + URLEncoder.encode(signature,StandardCharsets.UTF_8.toString()) + "\" ";
    return headers;
}

SCRIPT、DEPLOY 和 REALM 字段如果您不需要,请删除它们

其他方法

public static String getMd5(String input) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] messageDigest = md.digest(input.getBytes());
    BigInteger no = new BigInteger(1, messageDigest);
    StringBuilder bld = new StringBuilder();
    String hashText = no.toString(16);
    bld.append(hashText);
    while (hashText.length() < 32) {
        bld.append("0");
    }
    return bld.toString();
}
public static String generateSignature(String msg, String keyString, String algoritmo) throws InvalidKeyException,
        NoSuchAlgorithmException {
    String digest;

    SecretKeySpec key = new SecretKeySpec(keyString.getBytes(StandardCharsets.UTF_8), algoritmo);
    Mac mac = Mac.getInstance(algoritmo);
    mac.init(key);
    byte[] bytes = mac.doFinal(msg.getBytes(StandardCharsets.US_ASCII));
    digest = Base64.getEncoder().encodeToString(bytes);

    return digest;
}

private String generateRandomString() throws NoSuchAlgorithmException {
    int largo=20;
    String [] carateres = ("0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,"
            + "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,S").split(",");
    StringBuilder randomString = new StringBuilder();
    Random random = SecureRandom.getInstanceStrong();
    for(int i=0; i<largo; i++){
        randomString.append(carateres[random.nextInt((carateres.length - 1))]);
    }
    return randomString.toString();
}

希望对大家有所帮助,问候

【讨论】:

    猜你喜欢
    • 2012-06-19
    • 2016-07-31
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 2014-12-25
    • 2012-08-18
    相关资源
    最近更新 更多