Friday, March 9, 2012

Windows Azure ACS - Windows Live Integration - Callback.aspx code samples

This post is follow up of Part 1 and Part 2.
Callback.aspx -



<%@ Page Language="C#" AutoEventWireup="true" Inherits="Avanade.AMMO.Web.Callback" Codebehind="Callback.aspx.cs" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>  
    <script src="//js.live.net/v5.0/wl.js" type="text/javascript" language="javascript"></script>
</head>
<body>
<form id="form2" runat="server">           
</form>
</body>
</html>

Callback.aspx.cs -

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;
using System.ServiceModel.Syndication;
using System.Xml.Xsl;
using System.Globalization;
using System.Xml.XPath;
using System.Collections;
using System.Dynamic;
using System.Collections.ObjectModel;
using System.Web.Script.Serialization;
using System.Configuration;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.IdentityModel.Claims;

public partial class Callback : System.Web.UI.Page
    {
        // read the following values from web role configuration file       
        private string clientId = RoleEnvironment.GetConfigurationSettingValue("LiveIdClientID");

        // Make sure this is identical to the redirect_uri parameter passed in WL.init() call.       
        private string callback = RoleEnvironment.GetConfigurationSettingValue("LiveIdRedirectURL");
        private string clientSecret = RoleEnvironment.GetConfigurationSettingValue("LiveIdClientSecret");       
        private string oauthUrl = RoleEnvironment.GetConfigurationSettingValue("LiveIdOAuthURL");

        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext context = HttpContext.Current;
           
            if (!string.IsNullOrEmpty(Request.QueryString[OAuthConstants.AccessToken]))
            {
                // There is a token available already. It should be the token flow. Ignore it.
                return;
            }

            string verifier = Request.QueryString[OAuthConstants.Code];
           
            if (!string.IsNullOrEmpty(verifier))
            {
                OAuthResponse oauthResponse = RequestAccessTokenByVerifier(verifier);

                if (oauthResponse.Error != null)
                {
                    if(!String.IsNullOrEmpty(oauthResponse.Error.Code))
                        throw new Exception("Error occured while getting Windows Live OAuth Token. Error Code: " + oauthResponse.Error.Code + " --- Description: " + oauthResponse.Error.Description);

                }

                if (oauthResponse.Token != null)
                {
                    string restcall = "https://apis.live.net/v5.0/me?access_token=" + oauthResponse.Token.AccessToken;
                    MakeWebRequest(restcall, oauthResponse.Token);
                }
                return;
            }

            string errorCode = Request.QueryString[OAuthConstants.Error];
            string errorDesc = Request.QueryString[OAuthConstants.ErrorDescription];

            if (!string.IsNullOrEmpty(errorCode))
            {
                throw new Exception("Error occured while getting Windows Live OAuth Token. Error Code: " + errorCode + " --- Description: " + errorDesc);
            }
        }
               
        private OAuthResponse RequestAccessTokenByVerifier(string verifier)
        {
            string content = String.Format("client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code",
                HttpUtility.UrlEncode(clientId),
                HttpUtility.UrlEncode(callback),
                HttpUtility.UrlEncode(clientSecret),
                HttpUtility.UrlEncode(verifier));

            return RequestAccessToken(content);
        }

        private OAuthResponse RequestAccessTokenByRefreshToken(string refreshToken)
        {
            string content = String.Format("client_id={0}&redirect_uri={1}&client_secret={2}&refresh_token={3}&grant_type=refresh_token",
                HttpUtility.UrlEncode(clientId),
                HttpUtility.UrlEncode(callback),
                HttpUtility.UrlEncode(clientSecret),
                HttpUtility.UrlEncode(refreshToken));

            return RequestAccessToken(content);
        }

        private OAuthResponse RequestAccessToken(string postContent)
        {
            OAuthResponse oauthResponse = new OAuthResponse();

            HttpWebRequest request = WebRequest.Create(oauthUrl) as HttpWebRequest;
            request.Method = "POST";

            try
            {
                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(postContent);
                }

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                if (response != null)
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(OAuthToken));
                    oauthResponse.Token = serializer.ReadObject(response.GetResponseStream()) as OAuthToken;                   
                }
            }
            catch (WebException e)
            {
                HttpWebResponse response = e.Response as HttpWebResponse;
                if (response != null)
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(OAuthError));
                    oauthResponse.Error = serializer.ReadObject(response.GetResponseStream()) as OAuthError;
                }
            }
            catch (IOException)
            {
            }

            return oauthResponse;
        }


        private void MakeWebRequest(string restCall, OAuthToken token)
        {
           
            // Make web request
            HttpWebRequest request = WebRequest.Create(restCall) as HttpWebRequest;
            //request.Headers["Authorization"] = token.AccessToken;
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                StreamReader jsonReader = new StreamReader(response.GetResponseStream());
                string jsonLiveIDData = jsonReader.ReadToEnd();               
                JavaScriptSerializer js = new JavaScriptSerializer();

                //all retrieved values are stored in WindowsLiveID object
                WindowsLiveID windowsLiveID = (WindowsLiveID)js.Deserialize(jsonLiveIDData, typeof(WindowsLiveID));
                               
                //add email to session
                Session["EmailAddress"] = windowsLiveID.Emails.Account;
                //Session["Principal"] = System.Threading.Thread.CurrentPrincipal;
                //redirect to default page of AMMO               
                Response.Redirect("Default.aspx");
            }                          
        }
}



    [DataContract]
    public class OAuthResponse
    {
        public OAuthToken Token { get; set; }
        public OAuthError Error { get; set; }
    }
    [DataContract]
    public class OAuthToken
    {
        [DataMember(Name = OAuthConstants.AccessToken)]
        public string AccessToken { get; set; } 
        [DataMember(Name = OAuthConstants.RefreshToken)]
        public string RefreshToken { get; set; } 

        [DataMember(Name = OAuthConstants.ExpiresIn)]
        public string ExpiresIn { get; set; } 
        [DataMember(Name = OAuthConstants.Scope)]
        public string Scope { get; set; }
    }   


 
    [DataContract]
    public class OAuthError
    {
        public OAuthError(string code, string desc)
        {
            this.Code = code;
            this.Description = desc;
        }
        [DataMember(Name = OAuthConstants.Error)]
        public string Code { get; private set; } 
        [DataMember(Name = OAuthConstants.ErrorDescription)]
        public string Description { get; private set; }
    }
     public class OAuthConstants
    {
        #region OAuth 2.0 standard parameters
        public const string ClientID = "client_id";
        public const string ClientSecret = "client_secret";
        public const string Callback = "redirect_uri";
        public const string ClientState = "state";
        public const string Scope = "scope";
        public const string Code = "code";
        public const string AccessToken = "access_token";
        public const string ExpiresIn = "expires_in";
        public const string RefreshToken = "refresh_token";
        public const string ResponseType = "response_type";
        public const string GrantType = "grant_type";
        public const string Error = "error";
        public const string ErrorDescription = "error_description";
        public const string Display = "display";
        #endregion
    }


     public class WindowsLiveID
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public string First_name { get; set; }
        public string Last_name { get; set; }
        public Email Emails { get; set; }
        public string Link { get; set; }
    }
    public class Email
    {
        public string Preferred { get; set; }
        public string Account { get; set; }
        public string Personal { get; set; }
        public string Business { get; set; }
    }

No comments:

Post a Comment