1

i have successfully got the key token for the above oauth authentication from Google provider through their api.

let us consider "access-token" is xxxii-xxxxx-xxx-xxxxx-xxxxx which has scope of https://www.googleapis.com/auth/userinfo.profile

now when i hit the browser with access token for retrieving user information values has

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

i am getting responses as

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

My problem is when i parse the above request through code i am not getting responses as i got through browser

the code which i used is

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);  

in response i am getting null reference .

and the error i got in the line

JObject jsonResp = JObject.Parse(userInfo);

as

Unexpected character encountered while parsing value: h. Line 1, position 1.

Stack trace:

at Newtonsoft.Json.JsonTextReader.ParseValue(Char currentChar) at Newtonsoft.Json.JsonTextReader.ReadInternal() at 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

Waiting for your valuable suggestions and comments

Dima
  • 6,721
  • 4
  • 24
  • 43
GowthamanSS
  • 1,434
  • 4
  • 33
  • 58

1 Answers1

3

Use this code to get user info:

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;

There is a good article about integration of dotnetopenoauth and google api: http://www.dotnetopenauth.net/documentation/securityscenarios/

Dima
  • 6,721
  • 4
  • 24
  • 43