繁体   English   中英

从令牌c#获取用户信息

[英]Get user info from token c#

我已成功通过他们的api从Google提供商那里获得了上述oauth身份验证的密钥令牌。

让我们认为“访问令牌”是xxxii-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)at Newtonsoft.Json.JsonTextReaderInad()at Newtonsoft.Json.JsonTextReaderInad()at Newtonsoft.Json.Linq.JObject.Load(JsonReader reader)at Newtonsoft.Json .Linq.Jarse.Parse(String json)位于_Default.getresponse(String token)的d:\\ Oauth \\ WebSite3 \\ Default.aspx.cs:第99行

等待您宝贵的建议和意见

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

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和google api整合的好文章: http//www.dotnetopenauth.net/documentation/securityscenarios/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM