2013-03-18 136 views
0

我已经通过api成功获得了Google提供者的上述oauth认证的关键标记。从令牌c获取用户信息#

让我们考虑“访问令牌”是三十二-XXXXX-XXX-XXXXX-XXXXX其中有https://www.googleapis.com/auth/userinfo.profile

范围现在,当我击中访问令牌的浏览器用于获取用户信息值有

https://www.googleapis.com/oauth2/v1/userinfo?access_token=xxxii-xxxxx-xxx-xxxxx-xxxxx; 

我得到的反应是

{ 
"id": "XXXXXXXXXXXXXX", 
"name": "XXXXXXXXXXXXXXXX", 
"given_name": "XXXXXXXXXXX", 
"family_name": "X", 
"picture": "XXXXXXXXXX/photo.jpg", 
"locale": "en" 
} 

我的问题是,当我救援人员到场解析上述请求唉代码我没有得到回应,因为我通过浏览器

的代码,我用得到的是

String userInfo = "https://www.googleapis.com/oauth2/v1/userinfo?access_token="+token; 
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(userInfo); 
HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); 
StreamReader sr = new StreamReader(resp.GetResponseStream()); 

sr.Close(); 

JObject jsonResp = JObject.Parse(userInfo); 
string info = ""; 
info += "<h3>" + jsonResp.Root["name"] + "</h3>"; 
info += "<img src='" + jsonResp.Root["picture"] + "' width='120'/><br/>"; 
info += "<br/>ID : " + jsonResp.Root["id"]; 
info += "<br/>Email : " + jsonResp.Root["email"]; 

Response.Write(info); 

响应我收到空引用。

和我行

JObject jsonResp = JObject.Parse(userInfo); 

了作为

意外字符错误遇到在解析值:H。行1,位置1

堆栈跟踪:

在Newtonsoft.Json.JsonTextReader.ParseValue(CHAR currentChar) 在Newtonsoft.Json.JsonTextReader.ReadInternal() 在Newtonsoft.Json。 JsonTextReader.Read() at Newtonsoft.Json.Linq.JObject.Load(JsonReader reader) at Newtonsoft.Json.Linq.JObject.Parse(String json) at _Default.getresponse(String token)in d:\ Oauth \ WebSite3 \ Default.aspx.cs:line 99

等待您的宝贵建议和意见

+3

你解析url'userInfo',而不是响应'sr'。 – Caramiriel 2013-03-18 07:42:04

+0

@ Caramiriel我从nr – GowthamanSS 2013-03-18 08:35:11

+0

得到nul回应你可以检查'HttpWebResponse resp'并将你的发现添加到问题中吗?也许它返回一个HTTP 404或500状态。 – Caramiriel 2013-03-18 09:18:05

回答

2

使用此代码来获取用户信息:

var userInfoUrl = "https://www.googleapis.com/oauth2/v1/userinfo"; 
var hc = new HttpClient(); 
hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken); 
var response = hc.GetAsync(userInfoUrl).Result; 
dynamic userInfo = response.Content.ReadAsAsync().Result; 
return userInfo; 

有大约dotnetopenoauth和谷歌API的整合的好文章:http://www.dotnetopenauth.net/documentation/securityscenarios/

+0

可以请你分享上述方法的参考DLL名称 – GowthamanSS 2013-03-18 08:32:30

+0

它们都是.net的一部分:System.Net.Http.dll – Dima 2013-03-18 08:52:35