现在的位置: 首页 > 程序设计> 正文
人人网的 OAuth2.0 认证实现
2011年07月02日 程序设计 暂无评论 ⁄ 被围观 3,516+

现在貌似只有人人网最开始使用了OAuth2.0的认证,估计后续这些SNS站点都开始实现了,相比较OAuth1.0来看,2.0的认证过程确实方便了很多。

OAuth2.0 认证流程:

Java代码实现:

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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package com.carey.renren.example;  
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Scanner;
import java.util.TreeMap;  
import com.carey.renren.RenRenHttpClient;
import com.carey.renren.RenRenOAuth;
import com.carey.renren.utils.RenRenHttpUtil;  
 
public class RenRenMain {      
 public static void main(String[] args) {        
    renrenRequest();    
 }      
 
 private static void renrenRequest() {        
  if (!java.awt.Desktop.isDesktopSupported()) {            
     System.err.println("Desktop is not supported (fatal)");            
     System.exit(1);        
  }          
 
  java.awt.Desktop desktop = java.awt.Desktop.getDesktop();          
  if (desktop == null || !desktop.isSupported(java.awt.Desktop.Action.BROWSE)) {            
      System.err.println("Desktop doesn't support the browse action");            
      System.exit(1);        
  }                  
 
  getAuthorizationCode(desktop);        
  //  界面返回:        
  //  <a href="http://graph.renren.com/oauth/login_success.html?code=ki2wk30AHg18KLWvriLA1rlf9tAUd1Um">http://graph.renren.com/oauth/login_success.html?code=ki2wk30AHg18KLWvriLA1rlf9tAUd1Um</a>                 
 
  getAccessToken(desktop);        
  // 界面返回:        
  //  {         //  "access_token": "143511|5.57d2ad88cdd22398c03a2fcbb3bbd229.86400.1306422000-1167553647",        
  // "expires_in": 88680,        
  // "scope": "email status_update publish_feed"        
  // }                  
 
  getSessionToken(desktop);        
  // 界面返回:        
  //{"renren_token":{"session_secret":"ca076de790d8fc2470cb7b9da2c936f9","expires_in":88667,        
  // "session_key":"5.57d2ad88cdd22398c03a2fcbb3bbd229.86400.1306422000-1167553647"},        
  // "oauth_token":"143511|5.57d2ad88cdd22398c03a2fcbb3bbd229.86400.1306422000-1167553647","user":{"id":1167553647}}
 
  testAPI();        
  //  获取用户基本信息,输出结果为:        
  // [{"uid":1167553647,"tinyurl":"<a href="http://hd34.xiaonei.com/photos/hd34/20080322/13/30/tiny_22p107.jpg","vip":1,"sex":1">http://hd34.xiaonei.com/photos/hd34/20080322/13/30/tiny_22p107.jpg","vip":1,"sex":1</a>,  
  //  "name":"周润生","star":1,"headurl":"<a href="http://hd34.xiaonei.com/photos/hd34/20080322/13/30/head_22p107.jpg","zidou":0">http://hd34.xiaonei.com/photos/hd34/20080322/13/30/head_22p107.jpg","zidou":0</a>}]
 }          
 
 private static void getAuthorizationCode(java.awt.Desktop desktop) {        
  System.out.println("get Authorization Code......");                  
  try {            
   String urlStr = RenRenOAuth.AuthorizationURL + "?" + "client_id="  + RenRenOAuth.APIKey + "&" + "response_type=code"
    + "&redirect_uri=" + RenRenOAuth.RedirectURL;            
   System.out.println("authorization url: n" + urlStr);              
   desktop.browse(new URI(urlStr));        
  } catch (Exception e) {            
   e.printStackTrace();        
  }    
 }  
 
 private static void getAccessToken(java.awt.Desktop desktop) {        
  System.out.println("get Access Token......");          
        System.out.println("Input your Authorization code:");       
  Scanner in = new Scanner(System.in);        
  String input = in.nextLine();          
 
  try {           
   String urlStr = RenRenOAuth.OAuthURL + "?" + "client_id=" + RenRenOAuth.APIKey + "&client_secret=" + RenRenOAuth.SecretKey + "&redirect_uri="    
    + RenRenOAuth.RedirectURL  + "&grant_type=authorization_code" + "&code=" + input;            
   System.out.println("access url: n" + urlStr);              
   desktop.browse(new URI(urlStr));        
  } catch (Exception e) {
   e.printStackTrace();
  }   
 }     
 
 private static void getSessionToken(java.awt.Desktop desktop) {
  System.out.println("get Session Token......");
  System.out.println("Input your Access token:"); 
  Scanner in = new Scanner(System.in);       
  String input = in.nextLine();                 
 
  try {            
   input = URLEncoder.encode(input, "UTF-8");       
  } catch (UnsupportedEncodingException e1) {            
   e1.printStackTrace();        
  }          
 
  try {            
   String urlStr = RenRenOAuth.SessionURL + "?" + "oauth_token=" + input;            
   System.out.println("session url: n" + urlStr);              
   desktop.browse(new URI(urlStr));        
  } catch (Exception e) {            
   e.printStackTrace();        
  }    
 }          
 
 private static void testAPI() {        
  System.out.println("Input your Session Token:");        
  //Scanner in = new Scanner(System.in);        
  //String input = in.nextLine();                  
  String input = "5.57d2ad88cdd22398c03a2fcbb3bbd229.86400.1306422000-1167553647";                  
  TreeMap params = new TreeMap();        
  params.put("session_key", input);        
 
  //params.put("method", "friends.get");                  
  params.put("method", "users.getInfo");        
  params.put("uids", "1167553647");                  
  String content = sendPostRestRequest(params, "JSON", RenRenOAuth.ApiUrl);        
  if (content.indexOf("error_code") >= 0) {            
   //error        
  }        
 
  System.out.println(content);    
 }          
 
 public static String sendPostRestRequest(TreeMap params, String format, String url) {       
  RenRenHttpUtil.prepareParams(params, format);        
  String content = RenRenHttpClient.doPost(url, params);        
  return content;    
 }
}
package com.carey.renren.example;  
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.Scanner;
import java.util.TreeMap;  
import com.carey.renren.RenRenHttpClient;
import com.carey.renren.RenRenOAuth;
import com.carey.renren.utils.RenRenHttpUtil;  

public class RenRenMain {      
 public static void main(String[] args) {        
    renrenRequest();    
 }      

 private static void renrenRequest() {        
  if (!java.awt.Desktop.isDesktopSupported()) {            
     System.err.println("Desktop is not supported (fatal)");            
     System.exit(1);        
  }          

  java.awt.Desktop desktop = java.awt.Desktop.getDesktop();          
  if (desktop == null || !desktop.isSupported(java.awt.Desktop.Action.BROWSE)) {            
      System.err.println("Desktop doesn't support the browse action");            
      System.exit(1);        
  }                  

  getAuthorizationCode(desktop);        
  //  界面返回:        
  //  <a href="http://graph.renren.com/oauth/login_success.html?code=ki2wk30AHg18KLWvriLA1rlf9tAUd1Um">http://graph.renren.com/oauth/login_success.html?code=ki2wk30AHg18KLWvriLA1rlf9tAUd1Um</a>                 

  getAccessToken(desktop);        
  // 界面返回:        
  //  {         //  "access_token": "143511|5.57d2ad88cdd22398c03a2fcbb3bbd229.86400.1306422000-1167553647",        
  // "expires_in": 88680,        
  // "scope": "email status_update publish_feed"        
  // }                  

  getSessionToken(desktop);        
  // 界面返回:        
  //{"renren_token":{"session_secret":"ca076de790d8fc2470cb7b9da2c936f9","expires_in":88667,        
  // "session_key":"5.57d2ad88cdd22398c03a2fcbb3bbd229.86400.1306422000-1167553647"},        
  // "oauth_token":"143511|5.57d2ad88cdd22398c03a2fcbb3bbd229.86400.1306422000-1167553647","user":{"id":1167553647}}

  testAPI();        
  //  获取用户基本信息,输出结果为:        
  // [{"uid":1167553647,"tinyurl":"<a href="http://hd34.xiaonei.com/photos/hd34/20080322/13/30/tiny_22p107.jpg","vip":1,"sex":1">http://hd34.xiaonei.com/photos/hd34/20080322/13/30/tiny_22p107.jpg","vip":1,"sex":1</a>,  
  //  "name":"周润生","star":1,"headurl":"<a href="http://hd34.xiaonei.com/photos/hd34/20080322/13/30/head_22p107.jpg","zidou":0">http://hd34.xiaonei.com/photos/hd34/20080322/13/30/head_22p107.jpg","zidou":0</a>}]
 }          

 private static void getAuthorizationCode(java.awt.Desktop desktop) {        
  System.out.println("get Authorization Code......");                  
  try {            
   String urlStr = RenRenOAuth.AuthorizationURL + "?" + "client_id="  + RenRenOAuth.APIKey + "&" + "response_type=code"
    + "&redirect_uri=" + RenRenOAuth.RedirectURL;            
   System.out.println("authorization url: n" + urlStr);              
   desktop.browse(new URI(urlStr));        
  } catch (Exception e) {            
   e.printStackTrace();        
  }    
 }  

 private static void getAccessToken(java.awt.Desktop desktop) {        
  System.out.println("get Access Token......");          
        System.out.println("Input your Authorization code:");       
  Scanner in = new Scanner(System.in);        
  String input = in.nextLine();          

  try {           
   String urlStr = RenRenOAuth.OAuthURL + "?" + "client_id=" + RenRenOAuth.APIKey + "&client_secret=" + RenRenOAuth.SecretKey + "&redirect_uri="    
    + RenRenOAuth.RedirectURL  + "&grant_type=authorization_code" + "&code=" + input;            
   System.out.println("access url: n" + urlStr);              
   desktop.browse(new URI(urlStr));        
  } catch (Exception e) {
   e.printStackTrace();
  }   
 }     

 private static void getSessionToken(java.awt.Desktop desktop) {
  System.out.println("get Session Token......");
  System.out.println("Input your Access token:"); 
  Scanner in = new Scanner(System.in);       
  String input = in.nextLine();                 

  try {            
   input = URLEncoder.encode(input, "UTF-8");       
  } catch (UnsupportedEncodingException e1) {            
   e1.printStackTrace();        
  }          

  try {            
   String urlStr = RenRenOAuth.SessionURL + "?" + "oauth_token=" + input;            
   System.out.println("session url: n" + urlStr);              
   desktop.browse(new URI(urlStr));        
  } catch (Exception e) {            
   e.printStackTrace();        
  }    
 }          

 private static void testAPI() {        
  System.out.println("Input your Session Token:");        
  //Scanner in = new Scanner(System.in);        
  //String input = in.nextLine();                  
  String input = "5.57d2ad88cdd22398c03a2fcbb3bbd229.86400.1306422000-1167553647";                  
  TreeMap params = new TreeMap();        
  params.put("session_key", input);        

  //params.put("method", "friends.get");                  
  params.put("method", "users.getInfo");        
  params.put("uids", "1167553647");                  
  String content = sendPostRestRequest(params, "JSON", RenRenOAuth.ApiUrl);        
  if (content.indexOf("error_code") >= 0) {            
   //error        
  }        

  System.out.println(content);    
 }          

 public static String sendPostRestRequest(TreeMap params, String format, String url) {       
  RenRenHttpUtil.prepareParams(params, format);        
  String content = RenRenHttpClient.doPost(url, params);        
  return content;    
 }
}

上面代码的实现过程和OAuth2.0的认证流程相互一致,其他主要功能函数实现如下:

1
2
3
4
5
6
7
8
//初始化公共的Http请求参数
public static TreeMap prepareParams(TreeMap params, String format) {    
 params.put("api_key", RenRenOAuth.APIKey);    
 params.put("v", RenRenOAuth.ApiVersion);    
 params.put("call_id", String.valueOf(System.currentTimeMillis()));    
 params.put("format", format);     
 return sigParams(params);
}
//初始化公共的Http请求参数
public static TreeMap prepareParams(TreeMap params, String format) {    
 params.put("api_key", RenRenOAuth.APIKey);    
 params.put("v", RenRenOAuth.ApiVersion);    
 params.put("call_id", String.valueOf(System.currentTimeMillis()));    
 params.put("format", format);     
 return sigParams(params);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 //进行参数的签名
public static TreeMap sigParams(TreeMap params) {    
 StringBuffer sb = new StringBuffer();    
 for (Iterator> iterator = params.entrySet().iterator(); iterator.hasNext();) {
  Map.Entry entry = (Map.Entry) iterator.next();        
  sb.append(entry.getKey());        
  sb.append("=");        
  sb.append(entry.getValue());    
 }    
 
 sb.append(RenRenOAuth.SecretKey);    
 params.put("sig", RenRenHttpUtil.md5(sb.toString()));    
 return params;
}
 //进行参数的签名
public static TreeMap sigParams(TreeMap params) {    
 StringBuffer sb = new StringBuffer();    
 for (Iterator> iterator = params.entrySet().iterator(); iterator.hasNext();) {
  Map.Entry entry = (Map.Entry) iterator.next();        
  sb.append(entry.getKey());        
  sb.append("=");        
  sb.append(entry.getValue());    
 }    

 sb.append(RenRenOAuth.SecretKey);    
 params.put("sig", RenRenHttpUtil.md5(sb.toString()));    
 return params;
}

程序的源代码:http://lovertest.googlecode.com/svn/trunk/RenRen4j

给我留言

留言无头像?


×
腾讯微博