基于 OAuth 安全协议的 Java 应用编程
2011-01-14 19:16 王克伟 阅读(4103) 评论(1) 编辑 收藏 举报原文地址:http://www.ibm.com/developerworks/cn/java/j-lo-oauth/index.html
OAuth 是由 Blaine Cook、Chris Messina、Larry Halff 及 David Recordon 共同发起的,目的在于为 API 访问授权提供一个安全、开放的标准。
基于 OAuth 认证授权具有以下特点:
- 安全。OAuth 与别的授权方式不同之处在于:OAuth 的授权不会使消费方(Consumer)触及到用户的帐号信息(如用户名与密码),也是是说,消费方无需使用用户的用户名与密码就可以申请获得该用户资源的授权。
- 开放。任何消费方都可以使用 OAuth 认证服务,任何服务提供方 (Service Provider) 都可以实现自身的 OAuth 认证服务。
- 简单。不管是消费方还是服务提供方,都很容易于理解与使用。
OAuth 的解决方案如下图所示。
如图 1 所示 OAuth 解决方案中用户、消费方及其服务提供方之间的三角关系:当用户需要 Consumer 为其提供某种服务时,该服务涉及到需要从服务提供方那里获取该用户的保护资源。OAuth 保证:只有在用户显式授权的情况下(步骤 4),消费方才可以获取该用户的资源,并用来服务于该用户。
从宏观层次来看,OAuth 按以下方式工作:
- 消费方与不同的服务提供方建立了关系。
- 消费方共享一个密码短语或者是公钥给服务提供方,服务提供方使用该公钥来确认消费方的身份。
- 消费方根据服务提供方将用户重定向到登录页面。
- 该用户登录后告诉服务提供方该消费方访问他的保护资源是没问题的。
在了解 OAuth 认证流程之前,我们先来了解一下 OAuth 协议的一些基本术语定义:
- Consumer Key:消费方对于服务提供方的身份唯一标识。
- Consumer Secret:用来确认消费方对于 Consumer Key 的拥有关系。
- Request Token:获得用户授权的请求令牌,用于交换 Access Token。
- Access Token:用于获得用户在服务提供方的受保护资源。
- Token Secret:用来确认消费方对于令牌(Request Token 和 Access Token)的拥有关系。
图 2. OAuth 授权流程(摘自 OAuth 规范)
对于图 2 具体每一执行步骤,解释如下:
- 消费方向 OAuth 服务提供方请求未授权的 Request Token。
- OAuth 服务提供方在验证了消费方的合法请求后,向其颁发未经用户授权的 Request Token 及其相对应的 Token Secret。
- 消费方使用得到的 Request Token,通过 URL 引导用户到服务提供方那里,这一步应该是浏览器的行为。接下来,用户可以通过输入在服务提供方的用户名 / 密码信息,授权该请求。一旦授权成功,转到下一步。
- 服务提供方通过 URL 引导用户重新回到消费方那里,这一步也是浏览器的行为。
- 在获得授权的 Request Token 后,消费方使用授权的 Request Token 从服务提供方那里换取 Access Token。
- OAuth 服务提供方同意消费方的请求,并向其颁发 Access Token 及其对应的 Token Secret。
- 消费方使用上一步返回的 Access Token 访问用户授权的资源。
总的来讲,在 OAuth 的技术体系里,服务提供方需要提供如下基本的功能:
- 第 1、实现三个 Service endpoints,即:提供用于获取未授权的 Request Token 服务地址,获取用户授权的 Request Token 服务地址,以及使用授权的 Request Token 换取 Access Token 的服务地址。
- 第 2、提供基于 Form 的用户认证,以便于用户可以登录服务提供方做出授权。
- 第 3、授权的管理,比如用户可以在任何时候撤销已经做出的授权。
而对于消费方而言,需要如下的基本功能:
- 第 1、从服务提供方获取 Customer Key/Customer Secret。
- 第 2、提供与服务提供方之间基于 HTTP 的通信机制,以换取相关的令牌。
我们具体来看一个使用 OAuth 认证的例子。
在传统的网站应用中,如果您想在网站 A 导入网站 B 的联系人列表,需要在网站 A 输入您网站 B 的用户名、密码信息。例如,您登陆 Plaxo (https://www.plaxo.com ),一个联系人管理网站,当您想把 GMail 的联系人列表导入到 Plaxo,您需要输入您的 GMail 用户名 / 密码,如图 3 所示:
在这里,Plaxo 承诺不会保存您在 Gmail 的密码。
如果使用 OAuth 认证,情况是不同的,您不需要向网站 A(扮演 Consumer 角色)暴露您网站 B(扮演 Service Provider 角色)的用户名、密码信息。例如,您登录 http://lab.madgex.com/oauth-net/googlecontacts/default.aspx 网站, 如图 4 所示:
图 4. 在 lab.madgex.com 获得 GMail 联系人
点击“Get my Google Contacts”,浏览器将会重定向到 Google,引导您登录 Google,如图 5 所示:
登录成功后,将会看到图 6 的信息:
图 6. Google 对 lab.madgex.com 网站授权
在您登录 Google,点击“Grant access”,授权 lab.madgex.com 后,lab.madgex.com 就能获得您在 Google 的联系人列表。
在上面的的例子中,网站 lab.madgex.com 扮演着 Consumer 的角色,而 Google 是 Service Provider,lab.madgex.com 使用基于 OAuth 的认证方式从 Google 获得联系人列表。
下一节,本文会给出一个消费方实现的例子,通过 OAuth 机制请求 Google Service Provider 的 OAuth Access Token,并使用该 Access Token 访问用户的在 Google 上的日历信息 (Calendar)。
作为消费方,首先需要访问 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,用于我们下面的开发工作。
以下的代码是基于 Google Code 上提供的 OAuth Java 库进行开发的,读者可以从 http://oauth.googlecode.com/svn/code/java/core/ 下载获得。
- 指定 Request Token URL,User Authorization URL,以及 Access Token URL,构造 OAuthServiceProvider 对象: 1234
OAuthServiceProvider serviceProvider =
new
OAuthServiceProvider(
- 指定 Customer Key,Customer Secret 以及 OAuthServiceProvider,构造 OAuthConsumer 对象:
1234
OAuthConsumer oauthConsumer =
new
OAuthConsumer(
null
,
"www.example.com"
,
"hIsGkM+T4+90fKNesTtJq8Gs"
, serviceProvider);
- 为 OAuthConsumer 指定签名方法,以及提供您自签名 X509 数字证书的 private key。
12
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 服务:
12
Collection<? extends Map.Entry> parameters
- 通过 OAuthClient 获得 Request Token:
12
OAuthMessage response = getOAuthClient().getRequestTokenResponse(
accessor,
null
, parameters);
使用 Request Token, 将用户重定向到授权页面,如图 7 所示:
- 当用户点击“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
使用 OAuth Access Token 访问 Google 服务
接下来,我们使用上一节获得的 Access Token 设置 Google Service 的 OAuth 认证参数,然后从 Google Service 获取该用户的 Calendar 信息:
1 2 3 4 | OAuthParameters para = new OAuthParameters(); para.setOAuthConsumerKey( "www.example.com" ); para.setOAuthToken(accessToken); googleService.setOAuthCredentials(para, signer); |
清单 1 是完整的示例代码,供读者参考。
清单 1. 基于 OAuth 认证的 Google Service 消费方实现
12345678910111213141516171819202122232425262728293031323334353637383940414243import 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;
}
}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697import 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
//used for authorizing the request token
//used for upgrading to an access token
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 =
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(
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 应用。
出处: http://wangkewei.cnblogs.com/
版权声明: 本文的版权归作者与博客园共有。转载时须注明本文的详细链接,否则作者将保留追究其法律责任的权利。
您可以从这里更方便的找到我的文章。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库