使用RestTemplate的OAuth 1授权标头

时间:2017-06-29 22:36:34

标签: spring oauth resttemplate

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

我曾尝试使用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来做呢?

1 个答案:

答案 0 :(得分:0)

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

 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();
}

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