Vladyslav Matviienko
Vladyslav Matviienko

Reputation: 10881

OAuth generate signature

I am trying to generate the signature for the OAuth request. Here is how I do it:

String toHash = URLEncoder.encode("POST&https://" + url + "&oauth_callback=oob&oauth_consumer_key=" + key + "&oauth_signature_method=HMAC-SHA1&oauth_timestamp=" + timeStamp + "&oauth_nonce=" + timeStamp);

String hash = computeHmac(toHash, secret);

...

public String computeHmac(String baseString, String key)
    {
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec secret = new SecretKeySpec(key.getBytes(), mac.getAlgorithm());
        mac.init(secret);
        byte[] digest = mac.doFinal(baseString.getBytes());
        return new String(Base64.encodeBase64(digest));
    }

But the server tells me that the signature is wrong. What am I am doing wrong? Pease help...

Upvotes: 1

Views: 1395

Answers (1)

Jcs
Jcs

Reputation: 13759

According to the OAuth specification:

The signature base string is constructed by concatenating together, in order, the following HTTP request elements:

  1. The HTTP request method in uppercase. For example: "HEAD", "GET", "POST", etc. If the request uses a custom HTTP method, it MUST be encoded (Section 3.6).

  2. An "&" character (ASCII code 38).

  3. The base string URI from Section 3.4.1.2, after being encoded (Section 3.6).

  4. An "&" character (ASCII code 38).

  5. The request parameters as normalized in Section 3.4.1.3.2, after being encoded (Section 3.6).

In your base string some chars are not correctly encoded and normalized. For instance:

https://             ->   https%3A%2F%2F
oauth_callback=oob   ->   oauth_callback%3Doob
...

All details about the string construction are here: https://www.rfc-editor.org/rfc/rfc5849#section-3.4.1.1

Upvotes: 3

Related Questions