基于 OAuth 安全协议的 Java 应用编程

1 篇文章 0 订阅

原文地址:http://www.ibm.com/developerworks/cn/java/j-lo-oauth/index.html

OAuth 简介

OAuth 是由 Blaine Cook、Chris Messina、Larry Halff 及 David Recordon 共同发起的,目的在于为 API 访问授权提供一个安全、开放的标准。

基于 OAuth 认证授权具有以下特点:

  • 安全。OAuth 与别的授权方式不同之处在于:OAuth 的授权不会使消费方(Consumer)触及到用户的帐号信息(如用户名与密码),也是是说,消费方无需使用用户的用户名与密码就可以申请获得该用户资源的授权。
  • 开放。任何消费方都可以使用 OAuth 认证服务,任何服务提供方 (Service Provider) 都可以实现自身的 OAuth 认证服务。
  • 简单。不管是消费方还是服务提供方,都很容易于理解与使用。

OAuth 的解决方案如下图所示。

图 1. OAuth Solution 
image001

如图 1 所示 OAuth 解决方案中用户、消费方及其服务提供方之间的三角关系:当用户需要 Consumer 为其提供某种服务时,该服务涉及到需要从服务提供方那里获取该用户的保护资源。OAuth 保证:只有在用户显式授权的情况下(步骤 4),消费方才可以获取该用户的资源,并用来服务于该用户。

从宏观层次来看,OAuth 按以下方式工作:

  1. 消费方与不同的服务提供方建立了关系。
  2. 消费方共享一个密码短语或者是公钥给服务提供方,服务提供方使用该公钥来确认消费方的身份。
  3. 消费方根据服务提供方将用户重定向到登录页面。
  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 规范)  

image002

对于图 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 所示:

图 3. 在 Plaxo 获得 GMail 联系人 
image003

在这里,Plaxo 承诺不会保存您在 Gmail 的密码。

如果使用 OAuth 认证,情况是不同的,您不需要向网站 A(扮演 Consumer 角色)暴露您网站 B(扮演 Service Provider 角色)的用户名、密码信息。例如,您登录 http://lab.madgex.com/oauth-net/googlecontacts/default.aspx 网站, 如图 4 所示:

图 4. 在 lab.madgex.com 获得 GMail 联系人 
image004

点击“Get my Google Contacts”,浏览器将会重定向到 Google,引导您登录 Google,如图 5 所示:

图 5. 登录 Google 
image005

登录成功后,将会看到图 6 的信息:

图 6. Google 对 lab.madgex.com 网站授权 
image006

在您登录 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,用于我们下面的开发工作。

如何获得 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(
  • 指定 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 
    image007

  • 当用户点击“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 
image008

使用 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 消费方实现    

 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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;
     }
  }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
             //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 =
             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(
         
         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 应用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值