googleapis / google-oauth-java-client

Google OAuth Client Library for Java

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

No way to use POST for OAuth1.0

daniel-dylag-openx opened this issue · comments

I want to use OAuthGetTemporaryToken to request token from a server that requires POST request. This class extends from AbstractOAuthGetToken which has field usePost which should do what expected, but there is no API to set this parameter so it's always false.
According to Javadoc this class is only used for OAuth 1.0a

OAuthGetTemporaryToken getTemporaryToken = new OAuthGetTemporaryToken("...");
signer.clientSharedSecret = "...";
getTemporaryToken.signer = signer;
getTemporaryToken.consumerKey = "...";
getTemporaryToken.callback = "...";
getTemporaryToken.usePost = true;  # ERROR: 'usePost' has protected access in 'com.google.api.client.auth.oauth.AbstractOAuthGetToken'`
getTemporaryToken.transport = new NetHttpTransport();
OAuthCredentialsResponse temporaryTokenResponse = getTemporaryToken.execute();

The workaround for now is to set this field reflectively:

  try {
            Field field = AbstractOAuthGetToken.class.getDeclaredField("usePost");
            field.setAccessible(true);
            field.set(token, true);
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }

In my case, after I use the workaround there is another related problem: the OAuth server my code is talking to expects Content-Length to be always set - in case of empty content, to 0. Otherwise, the server throws 411 error and token generation cannot be finished.

In order to fix this, we could change the line in AbstractOAuthGetToken
from
HttpRequest request = requestFactory.buildRequest(usePost ? HttpMethods.POST : HttpMethods.GET, this, null);
to
HttpRequest request = requestFactory.buildRequest(usePost ? HttpMethods.POST : HttpMethods.GET, this, usePost ? new EmptyContent() : null);

As per EmptyContent's doc, this class exists to solve this exact problem:

Note that there is no Content-Length header if the HTTP request content is 
null. However, when making a request like PUT or POST without a Content-Length header,
some servers may respond with a 411 Length Required error. Specifying the
Content-Length: 0 header may work around that problem.