我一直在寻找使用google oauth java软件包进行身份验证的示例: https://code.google.com/p/google-oauth-java-client/
我已经设法找到使用此软件包进行oauth2身份验证的示例,但我找不到任何oauth1。该文档简要概述了“典型的应用程序流程”,但它没有列出所有细节。
有没有人对我在哪里找到使用thing包的oauth1身份验证示例有任何建议?
答案 0 :(得分:11)
根据google-oauth-java-client JavaDoc和Google's OAuth 1.0 guide中的RFC 5849,示例应如下所示:
OAuthHmacSigner signer = new OAuthHmacSigner();
// Get Temporary Token
OAuthGetTemporaryToken getTemporaryToken = new OAuthGetTemporaryToken(TOKEN_SERVER_URL);
signer.clientSharedSecret = OAuth2ClientCredentials.CONSUMER_SECRET;
getTemporaryToken.signer = signer;
getTemporaryToken.consumerKey = OAuth2ClientCredentials.CONSUMER_KEY;
getTemporaryToken.transport = new NetHttpTransport();
OAuthCredentialsResponse temporaryTokenResponse = getTemporaryToken.execute();
// Build Authenticate URL
OAuthAuthorizeTemporaryTokenUrl accessTempToken = new OAuthAuthorizeTemporaryTokenUrl(AUTHENTICATE_URL);
accessTempToken.temporaryToken = temporaryTokenResponse.token;
String authUrl = accessTempToken.build();
// Redirect to Authenticate URL in order to get Verifier Code
System.out.println(authUrl);
// Get Access Token using Temporary token and Verifier Code
OAuthGetAccessToken getAccessToken = new OAuthGetAccessToken(ACCESS_TOKEN_URL);
getAccessToken.signer = signer;
getAccessToken.temporaryToken=temporaryTokenResponse.token;
getAccessToken.transport = new NetHttpTransport();
getAccessToken.verifier= "VERIFIER_CODE";
getAccessToken.consumerKey = OAuth2ClientCredentials.CONSUMER_KEY;
OAuthCredentialsResponse accessTokenResponse = getAccessToken.execute();
// Build OAuthParameters in order to use them while accessing the resource
OAuthParameters oauthParameters = new OAuthParameters();
signer.tokenSharedSecret = accessTokenResponse.tokenSecret;
oauthParameters.signer = signer;
oauthParameters.consumerKey = OAuth2ClientCredentials.CONSUMER_KEY;
oauthParameters.token = accessTokenResponse.token;
oauthParameters.verifier = "VERIFIER_CODE";
// Use OAuthParameters to access the desired Resource URL
HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory(oauthParameters);
GenericUrl genericUrl = new GenericUrl("RESOURCE_URL");
HttpResponse response = requestFactory.buildGetRequest(genericUrl).execute();
System.out.println(response.parseAsString());
希望这有帮助。
答案 1 :(得分:2)
以上示例非常有用。
关于将此lib与非标准oAuth 1.0实现一起使用的说明。我使用的是Goodreads oAuth API,它似乎是oAuth Bible所谓的“失败的OAuth 1.0a 3-legged实现”,这意味着它在重定向授权后不会发回验证码用户返回您的回调网址。在这种情况下,您需要删除上面提到VERIFIER_CODE的所有行并添加:
signer.tokenSharedSecret = temporaryTokenResponse.tokenSecret;
行之前:
OAuthCredentialsResponse accessTokenResponse = getAccessToken.execute();
我花了一段时间才弄清楚,所以希望能帮助别人。