基于 OAuth 安全协议的 Java 应用编程
2010-03-22 00:00:00 来源:WEB开发网当用户点击“Grant access”按钮,完成授权后,再次通过 OAuthClient 获得 Access Token:
oauthClient.getAccessToken(accessor, null, null);
在上述步骤成功完成后,Access Token 将保存在 accessor 对象的 accessToken 成员变量里。查看您的 Google Account 安全管理页面,可以看到您授权的所有消费方,如图 8 所示。
图 8. Authorized OAuth Access to your Google Account
查看原图(大图)
使用 OAuth Access Token 访问 Google 服务
接下来,我们使用上一节获得的 Access Token 设置 Google Service 的 OAuth 认证参数,然后从 Google Service 获取该用户的 Calendar 信息:
OAuthParameters para = new OAuthParameters();
para.setOAuthConsumerKey("www.example.com");
para.setOAuthToken(accessToken);
googleService.setOAuthCredentials(para, signer);
清单 1 是完整的示例代码,供读者参考。
清单 1. 基于 OAuth 认证的 Google Service 消费方实现
import java.util.Collection;
import java.util.Map;
import net.oauth.OAuth;
import net.oauth.OAuthAccessor;
import net.oauth.OAuthConsumer;
import net.oauth.client.OAuthClient;
public class DesktopClient {
private final OAuthAccessor accessor;
private OAuthClient oauthClient = null;
public DesktopClient(OAuthConsumer consumer) {
accessor = new OAuthAccessor(consumer);
}
public OAuthClient getOAuthClient() {
return oauthClient;
}
public void setOAuthClient(OAuthClient client) {
this.oauthClient = client;
}
//get the OAuth access token.
public String getAccessToken(String httpMethod,
Collection<? extends Map.Entry> parameters) throws Exception {
getOAuthClient().getRequestTokenResponse(accessor, null,parameters);
String authorizationURL = OAuth.addParameters(
accessor.consumer.serviceProvider.userAuthorizationURL,
OAuth.OAUTH_TOKEN, accessor.requestToken);
//Launch the browser and redirects user to authorization URL
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "
+ authorizationURL);
//wait for user's authorization
System.out.println("Please authorize your OAuth request token. "
+ "Once that is complete, press any key to continue...");
System.in.read();
oauthClient.getAccessToken(accessor, null, null);
return accessor.accessToken;
}
}
import java.net.URL;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Collection;
import java.util.Map;
import com.google.gdata.client.GoogleService;
import com.google.gdata.client.authn.oauth.OAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthRsaSha1Signer;
import com.google.gdata.client.authn.oauth.OAuthSigner;
import com.google.gdata.data.BaseEntry;
import com.google.gdata.data.BaseFeed;
import com.google.gdata.data.Feed;
import net.oauth.OAuth;
import net.oauth.OAuthConsumer;
import net.oauth.OAuthMessage;
import net.oauth.OAuthServiceProvider;
import net.oauth.client.OAuthClient;
import net.oauth.client.httpclient4.HttpClient4;
import net.oauth.example.desktop.MyGoogleService;
import net.oauth.signature.OAuthSignatureMethod;
import net.oauth.signature.RSA_SHA1;
public class GoogleOAuthExample {
//Note, use the private key of your self-signed X509 certificate.
private static final String PRIVATE_KEY = "XXXXXXXX";
public static void main(String[] args) throws Exception {
KeyFactory fac = KeyFactory.getInstance("RSA");
//PRIVATE_KEY is the private key of your self-signed X509 certificate.
EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(
OAuthSignatureMethod.decodeBase64(PRIVATE_KEY));
fac = KeyFactory.getInstance("RSA");
PrivateKey privateKey = fac.generatePrivate(privKeySpec);
OAuthServiceProvider serviceProvider = new OAuthServiceProvider(
//used for obtaining a request token
//"https://www.google.com/accounts/OAuthGetRequestToken",
//used for authorizing the request token
"https://www.google.com/accounts/OAuthAuthorizeToken",
//used for upgrading to an access token
"https://www.google.com/accounts/OAuthGetAccessToken");
OAuthConsumer oauthConsumer = new OAuthConsumer(null
, "lszhy.weebly.com" //consumer key
, "hIsGnM+T4+86fKNesUtJq7Gs" //consumer secret
, serviceProvider);
oauthConsumer.setProperty(OAuth.OAUTH_SIGNATURE_METHOD, OAuth.RSA_SHA1);
oauthConsumer.setProperty(RSA_SHA1.PRIVATE_KEY, privateKey);
DesktopClient client = new DesktopClient(oauthConsumer);
client.setOAuthClient(new OAuthClient(new HttpClient4()));
Collection<? extends Map.Entry> parameters =
OAuth.newList("scope","http://www.google.com/calendar/feeds/");
String accessToken = client.getAccessToken(OAuthMessage.GET,parameters);
//Make an OAuth authorized request to Google
// Initialize the variables needed to make the request
URL feedUrl = new URL(
"http://www.google.com/calendar/feeds/default/allcalendars/full");
System.out.println("Sending request to " + feedUrl.toString());
System.out.println();
GoogleService googleService = new GoogleService("cl", "oauth-sample-app");
OAuthSigner signer = new OAuthRsaSha1Signer(MyGoogleService.PRIVATE_KEY);
// Set the OAuth credentials which were obtained from the step above.
OAuthParameters para = new OAuthParameters();
para.setOAuthConsumerKey("lszhy.weebly.com");
para.setOAuthToken(accessToken);
googleService.setOAuthCredentials(para, signer);
// Make the request to Google
BaseFeed resultFeed = googleService.getFeed(feedUrl, Feed.class);
System.out.println("Response Data:");
System.out.println("==========================================");
System.out.println("|TITLE: " + resultFeed.getTitle().getPlainText());
if (resultFeed.getEntries().size() == 0) {
System.out.println("|\tNo entries found.");
} else {
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
BaseEntry entry = (BaseEntry) resultFeed.getEntries().get(i);
System.out.println("|\t" + (i + 1) + ": "
+ entry.getTitle().getPlainText());
}
}
System.out.println("==========================================");
}
}
小结
OAuth 协议作为一种开放的,基于用户登录的授权认证方式,目前互联网很多 Open API 都对 OAuth 提供了支持,这包括 Google, Yahoo,Twitter 等。本文以 Google 为例子,介绍了 Java 桌面程序如何开发 OAuth 认证应用。在开发桌面应用访问 Web 资源这样一类程序时,一般通行的步骤是:使用 OAuth 做认证,然后使用获得的 OAuth Access Token,通过 REST API 访问用户在服务提供方的资源。
事实上,目前 OAuth 正通过许多实现(包括针对 Java、C#、Objective-C、Perl、PHP 及 Ruby 语言的实现)获得巨大的动力。大部分实现都由 OAuth 项目维护并放在 Google 代码库 (http://oauth.googlecode.com/svn/) 上。开发者可以利用这些 OAuth 类库编写自己需要的 OAuth 应用。
更多精彩
赞助商链接