Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Live Connect API in ASP.NET to retrieve a user's email address

So I am fairly new to ASP.NET MVC and Windows Live Connect API. Basically I am trying to integrate Live sign in into my website. When users sign in, Live requests their permission to give my app certain info, sends the user to a redirect uri specified in my app settings appended with a querystring. Here, if the user is signing into the site for the first time, I want their basic info stored on my server (first name, last name, email). I have been able to get their first and last name, but am having a hard time finding out how to retrieve their primary email address. I'll explain what I've done so far.

I couldn't find the best way to integrate Live connect into an MVC app so I took my best guess. I specified a controller action in my redirect uri that takes the querystring "code" to construct an HTTP Post.

HttpRequest req = System.Web.HttpContext.Current.Request;

            string myAuthCode = req.QueryString["code"];
            string myAppId = ConfigurationManager.AppSettings.Get("wll_appid");
            string mySecret = ConfigurationManager.AppSettings.Get("wll_secret");
            string postData = "client_id=" + myAppId + "&redirect_uri=http%3A%2F%2Fmscontestplatformtest.com%2FContestPlatform%2FUser%2FSignIn&client_secret=" + mySecret + "&code=" + myAuthCode + "&grant_type=authorization_code";

            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            WebRequest request = WebRequest.Create("https://oauth.live.com/token");
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            request.Method = "POST";

Get the JSON-formatted string response and extract the access_token. Then I use this access token to construct an HTTP GET call as follows.

request = WebRequest.Create("https://apis.live.net/v5.0/me?access_token=" + r.access_token);
            response = request.GetResponse();
            reader = new StreamReader(response.GetResponseStream());

            string userInfo = reader.ReadToEnd(); 

The GET call above provides me with this JSON string:

{ 
    "id": "02b4b930697bbea1", 
    "name": "Daniel Hines", 
    "first_name": "Daniel", 
    "last_name": "Hines", 
    "link": "http://profile.live.com/cid-02b4b930697bbea1/", 
    "gender": "male", 
    "locale": "en_US", 
    "updated_time": "2011-10-14T21:40:38+0000" 
} 

Which is all public info and is great, I have almost everything I need except their primary email address. What sort of GET call do I need to retrieve email?

Also, am I doing this right way?

like image 347
Danny Avatar asked Mar 19 '12 08:03

Danny


1 Answers

Ok I figured it out!

I just needed to add the scope "wl.emails" to my sign in link. Then my GET call will return their email addresses.

like image 91
Danny Avatar answered Oct 27 '22 12:10

Danny