基于 OAuth 安全协议的 Java 应用编程(3)示例
 
- UID
- 1066743
|

基于 OAuth 安全协议的 Java 应用编程(3)示例
示例准备工作作为消费方,首先需要访问 https://www.google.com/accounts/ManageDomains,从 Google 那里获得标志我们身份的 Customer Key 及其 Customer Secret。另外,您可以生成自己的自签名 X509 数字证书,并且把证书上传给 Google,Google 将会使用证书的公钥来验证任何来自您的请求。
具体的操作步骤,请读者参考 Google 的说明文档:http://code.google.com/apis/gdata/articles/oauth.html。
在您完成这些工作,您将会得到 OAuth Consumer Key 及其 OAuth Consumer Secret,用于我们下面的开发工作。
如何获得 OAuth Access Token以下的代码是基于 Google Code 上提供的 OAuth Java 库进行开发的,读者可以从 http://oauth.googlecode.com/svn/code/java/core/ 下载获得。
- 指定 Request Token URL,User Authorization URL,以及 Access Token URL,构造 OAuthServiceProvider 对象:
1
2
3
4
| OAuthServiceProvider serviceProvider = new OAuthServiceProvider(
"https://www.google.com/accounts/OAuthGetRequestToken",
"https://www.google.com/accounts/OAuthAuthorizeToken",
"https://www.google.com/accounts/OAuthGetAccessToken");
|
- 指定 Customer Key,Customer Secret 以及 OAuthServiceProvider,构造 OAuthConsumer 对象:
1
2
3
4
| OAuthConsumer oauthConsumer = new OAuthConsumer(null
, "www.example.com"
, "hIsGkM+T4+90fKNesTtJq8Gs"
, serviceProvider);
|
- 为 OAuthConsumer 指定签名方法,以及提供您自签名 X509 数字证书的 private key。
1
2
| oauthConsumer.setProperty(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.RSA_SHA1);
oauthConsumer.setProperty(RSA_SHA1.PRIVATE_KEY, privateKey);
|
- 由 OAuthConsumer 对象生成相应的 OAuthAccessor 对象:
1
| accessor = new OAuthAccessor(consumer);
|
- 指定您想要访问的 Google 服务,在这里我们使用的是 Calendar 服务:
1
2
| Collection<? extends Map.Entry> parameters
= OAuth.newList("scope","http://www.google.com/calendar/feeds/");
|
- 通过 OAuthClient 获得 Request Token:
1
2
| OAuthMessage response = getOAuthClient().getRequestTokenResponse(
accessor, null, parameters);
|
使用 Request Token, 将用户重定向到授权页面,如图 7 所示:
图 7. OAuth User Authorization - 当用户点击“Grant access”按钮,完成授权后,再次通过 OAuthClient 获得 Access Token:
1
| oauthClient.getAccessToken(accessor, null, null);
|
在上述步骤成功完成后,Access Token 将保存在 accessor 对象的 accessToken 成员变量里。查看您的 Google Account 安全管理页面,可以看到您授权的所有消费方,如图 8 所示。
图 8. Authorized OAuth Access to your Google Account |
|
|
|
|
|