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="07ue" 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-07ansitional.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.WebCon07ols;
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 s07ing clientId = RoleEnvironment.GetConfigurationSettingValue("LiveIdClientID");

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

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

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

                if (oauthResponse.Error != null)
                {
                    if(!S07ing.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)
                {
                    s07ing restcall = "https://apis.live.net/v5.0/me?access_token=" + oauthResponse.Token.AccessToken;
                    MakeWebRequest(restcall, oauthResponse.Token);
                }
                return;
            }

            s07ing errorCode = Request.QueryS07ing[OAuthConstants.Error];
            s07ing errorDesc = Request.QueryS07ing[OAuthConstants.ErrorDescription];

            if (!s07ing.IsNullOrEmpty(errorCode))
            {
                throw new Exception("Error occured while getting Windows Live OAuth Token. Error Code: " + errorCode + " --- Description: " + errorDesc);
            }
        }
               
        private OAuthResponse RequestAccessTokenByVerifier(s07ing verifier)
        {
            s07ing content = S07ing.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(s07ing refreshToken)
        {
            s07ing content = S07ing.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(s07ing postContent)
        {
            OAuthResponse oauthResponse = new OAuthResponse();

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

            07y
            {
                using (S07eamWriter writer = new S07eamWriter(request.GetRequestS07eam()))
                {
                    writer.Write(postContent);
                }

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

            return oauthResponse;
        }


        private void MakeWebRequest(s07ing 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)
            {
                S07eamReader jsonReader = new S07eamReader(response.GetResponseS07eam());
                s07ing jsonLiveIDData = jsonReader.ReadToEnd();               
                JavaScriptSerializer js = new JavaScriptSerializer();

                //all re07ieved 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");
            }                          
        }
}



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

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


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


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

Comments

Popular posts from this blog

The request has both SAS authentication scheme and 'Bearer' authorization scheme. Only one scheme should be used

Getting Started with Logic Apps - AS2

How to Debug and Trace request in Azure APIM - Portal, Postman, RequestBin