/// <summary>
    /// This method gets access token based on either client credentials mode or refresh token.
    /// </summary>
    /// <param name="type">AccessTokenType; either Client_Credential or Refresh_Token</param>
    /// <returns>true/false; true if able to get access token, else false</returns>
    private bool GetAccessToken(AccessTokenType type)
    {
        Stream postStream = null;
        StreamWriter streamWriter = null;
        FileStream fileStream = null;
        try
        {
            DateTime currentServerTime = DateTime.UtcNow.ToLocalTime();

            WebRequest accessTokenRequest = System.Net.HttpWebRequest.Create(string.Empty + this.endPoint + "/oauth/token");
            accessTokenRequest.Method = "POST";

            string oauthParameters = string.Empty;
            if (type == AccessTokenType.Client_Credential)
            {
                oauthParameters = "client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&grant_type=client_credentials&scope=MMS";
            }
            else
            {
                oauthParameters = "grant_type=refresh_token&client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&refresh_token=" + this.refreshToken;
            }

            accessTokenRequest.ContentType = "application/x-www-form-urlencoded";

            UTF8Encoding encoding = new UTF8Encoding();

            byte[] postBytes = encoding.GetBytes(oauthParameters);
            accessTokenRequest.ContentLength = postBytes.Length;

            postStream = accessTokenRequest.GetRequestStream();
            postStream.Write(postBytes, 0, postBytes.Length);

            WebResponse accessTokenResponse = accessTokenRequest.GetResponse();

            using (StreamReader accessTokenResponseStream = new StreamReader(accessTokenResponse.GetResponseStream()))
            {
                string jsonAccessToken = accessTokenResponseStream.ReadToEnd();
                JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
                AccessTokenResponse deserializedJsonObj = (AccessTokenResponse)deserializeJsonObject.Deserialize(jsonAccessToken, typeof(AccessTokenResponse));

                this.accessToken = deserializedJsonObj.access_token;
                this.expirySeconds = deserializedJsonObj.expires_in;
                this.refreshToken = deserializedJsonObj.refresh_token;
                this.accessTokenExpiryTime = currentServerTime.AddSeconds(Convert.ToDouble(deserializedJsonObj.expires_in));

                DateTime refreshExpiry = currentServerTime.AddHours(this.refreshTokenExpiresIn);

                if (deserializedJsonObj.expires_in.Equals("0"))
                {
                    int defaultAccessTokenExpiresIn = 100; // In Years
                    this.accessTokenExpiryTime = currentServerTime.AddYears(defaultAccessTokenExpiresIn);
                }

                this.refreshTokenExpiryTime = refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString();

                fileStream = new FileStream(Request.MapPath(this.accessTokenFilePath), FileMode.OpenOrCreate, FileAccess.Write);
                streamWriter = new StreamWriter(fileStream);

                streamWriter.WriteLine(this.accessToken);
                streamWriter.WriteLine(this.expirySeconds);
                streamWriter.WriteLine(this.refreshToken);
                streamWriter.WriteLine(this.accessTokenExpiryTime.ToString());
                streamWriter.WriteLine(this.refreshTokenExpiryTime);

                // Close and clean up the StreamReader
                accessTokenResponseStream.Close();

                return true;
            }
        }
        catch (WebException we)
        {
            string errorResponse = string.Empty;

            try
            {
                using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream()))
                {
                    errorResponse = sr2.ReadToEnd();
                    sr2.Close();
                }
            }
            catch
            {
                errorResponse = "Unable to get response";
            }
            this.DrawPanelForFailure(sendMessagePanel, errorResponse + Environment.NewLine + we.Message);
        }
        catch (Exception ex)
        {
            this.DrawPanelForFailure(sendMessagePanel, ex.ToString());
        }
        finally
        {
            if (null != postStream)
            {
                postStream.Close();
            }

            if (null != streamWriter)
            {
                streamWriter.Close();
            }

            if (null != fileStream)
            {
                fileStream.Close();
            }
        }
        return false;
    }
    /// <summary>
    /// Get access token based on the type parameter type values.
    /// </summary>
    /// <param name="type">If type value is Authorization_code, access token is fetch for authorization code flow
    /// If type value is Refresh_Token, access token is fetch for authorization code flow based on the exisiting refresh token</param>
    /// <returns>true/false; true if success, else false</returns>
    private bool GetAccessToken(AccessTokenType type)
    {
        Stream postStream = null;
        try
        {
            DateTime currentServerTime = DateTime.UtcNow.ToLocalTime();
            WebRequest accessTokenRequest = System.Net.HttpWebRequest.Create(string.Empty + this.endPoint + "/oauth/token");
            accessTokenRequest.Method = "POST";

            string oauthParameters = string.Empty;

            if (type == AccessTokenType.Authorization_Code)
            {
                oauthParameters = "client_id=" + this.apiKey.ToString() + "&client_secret=" + this.secretKey + "&code=" + this.authCode + "&grant_type=authorization_code&scope=" + this.scope;
            }
            else if (type == AccessTokenType.Refresh_Token)
            {
                oauthParameters = "grant_type=refresh_token&client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&refresh_token=" + this.refreshToken;
            }

            accessTokenRequest.ContentType = "application/x-www-form-urlencoded";
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] postBytes = encoding.GetBytes(oauthParameters);
            accessTokenRequest.ContentLength = postBytes.Length;
            postStream = accessTokenRequest.GetRequestStream();
            postStream.Write(postBytes, 0, postBytes.Length);
            postStream.Close();

            WebResponse accessTokenResponse = accessTokenRequest.GetResponse();
            using (StreamReader accessTokenResponseStream = new StreamReader(accessTokenResponse.GetResponseStream()))
            {
                string access_token_json = accessTokenResponseStream.ReadToEnd();
                JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
                AccessTokenResponse deserializedJsonObj = (AccessTokenResponse)deserializeJsonObject.Deserialize(access_token_json, typeof(AccessTokenResponse));
                if (deserializedJsonObj.access_token != null)
                {
                    this.accessToken = deserializedJsonObj.access_token;
                    this.refreshToken = deserializedJsonObj.refresh_token;
                    this.accessTokenExpiryTime = currentServerTime.AddSeconds(Convert.ToDouble(deserializedJsonObj.expires_in)).ToString();

                    DateTime refreshExpiry = currentServerTime.AddHours(this.refreshTokenExpiresIn);

                    if (deserializedJsonObj.expires_in.Equals("0"))
                    {
                        int defaultAccessTokenExpiresIn = 100; // In Years
                        this.accessTokenExpiryTime = currentServerTime.AddYears(defaultAccessTokenExpiresIn).ToString();
                    }

                    this.refreshTokenExpiryTime = refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString();

                    Session["tl_session_access_token"] = this.accessToken;
                    Session["tl_session_refresh_token"] = this.refreshToken;
                    Session["tl_session_accessTokenExpiryTime"] = this.accessTokenExpiryTime;
                    Session["tl_session_refreshTokenExpiryTime"] = this.refreshTokenExpiryTime;
                    Session["tl_session_appState"] = "TokenReceived";

                    accessTokenResponseStream.Close();
                    return true;
                }
                else
                {
                    this.DrawPanelForFailure(tlPanel, "Auth server returned null access token");
                }
            }
        }
        catch (WebException we)
        {
            if (null != we.Response)
            {
                using (Stream stream = we.Response.GetResponseStream())
                {
                    StreamReader streamReader = new StreamReader(stream);
                    this.DrawPanelForFailure(tlPanel, streamReader.ReadToEnd());
                    streamReader.Close();
                }
            }
        }
        catch (Exception ex)
        {
            this.DrawPanelForFailure(tlPanel, ex.Message);
        }
        finally
        {
            if (null != postStream)
            {
                postStream.Close();
            }
        }

        return false;
    }
    private bool GetAccessToken(AccessTokenType type)
    {
        Stream postStream = null;
        try
        {
            DateTime currentServerTime = DateTime.UtcNow.ToLocalTime();
            WebRequest accessTokenRequest = System.Net.HttpWebRequest.Create(string.Empty + this.endPoint + "/oauth/token");
            accessTokenRequest.Method = "POST";
            string oauthParameters = string.Empty;

            if (type == AccessTokenType.Authorization_Code)
            {
                oauthParameters = "client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&code=" + this.authCode + "&grant_type=authorization_code&scope=" + this.scope;
            }
            else
            {
                oauthParameters = "grant_type=refresh_token&client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&refresh_token=" + this.refreshToken;
            }

            accessTokenRequest.ContentType = "application/x-www-form-urlencoded";
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] postBytes = encoding.GetBytes(oauthParameters);
            accessTokenRequest.ContentLength = postBytes.Length;
            postStream = accessTokenRequest.GetRequestStream();
            postStream.Write(postBytes, 0, postBytes.Length);
            postStream.Close();

            WebResponse accessTokenResponse = accessTokenRequest.GetResponse();
            using (StreamReader accessTokenResponseStream = new StreamReader(accessTokenResponse.GetResponseStream()))
            {
                string access_token_json = accessTokenResponseStream.ReadToEnd();
                JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
                AccessTokenResponse deserializedJsonObj = (AccessTokenResponse)deserializeJsonObject.Deserialize(access_token_json, typeof(AccessTokenResponse));
                if (deserializedJsonObj.access_token != null)
                {
                    this.accessToken = deserializedJsonObj.access_token;
                    this.refreshToken = deserializedJsonObj.refresh_token;

                    DateTime refreshExpiry = currentServerTime.AddHours(this.refreshTokenExpiresIn);

                    Session["cs_rest_AccessTokenExpirtyTime"] = currentServerTime.AddSeconds(Convert.ToDouble(deserializedJsonObj.expires_in));

                    if (deserializedJsonObj.expires_in.Equals("0"))
                    {
                        int defaultAccessTokenExpiresIn = 100; // In Years
                        Session["cs_rest_AccessTokenExpirtyTime"] = currentServerTime.AddYears(defaultAccessTokenExpiresIn);
                    }

                    this.refreshTokenExpiryTime = refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString();

                    Session["cs_rest_AccessToken"] = this.accessToken;

                    this.accessTokenExpiryTime = Session["cs_rest_AccessTokenExpirtyTime"].ToString();
                    Session["cs_rest_RefreshToken"] = this.refreshToken;
                    Session["cs_rest_RefreshTokenExpiryTime"] = this.refreshTokenExpiryTime.ToString();
                    Session["cs_rest_appState"] = "TokenReceived";
                    accessTokenResponseStream.Close();
                    return true;
                }
                else
                {
                    string errorMessage = "Auth server returned null access token";
                    if (Session["cs_rest_ServiceRequest"] != null && (string.Compare(Session["cs_rest_ServiceRequest"].ToString(),
                                                            "sendmessasge") == 0))
                    {
                        sendMessageErrorResponse = errorMessage;
                    }
                    else if (Session["cs_rest_ServiceRequest"] != null && (string.Compare(Session["cs_rest_ServiceRequest"].ToString(),
                                        "createmessageindex") == 0))
                    {
                        createMessageIndexErrorResponse = errorMessage;
                    }
                    else if (Session["cs_rest_ServiceRequest"] != null && (string.Compare(Session["cs_rest_ServiceRequest"].ToString(),
                                        "getnotificationconnectiondetails") == 0))
                    {
                        getNotificationConnectionDetailsErrorResponse = errorMessage;
                    }
                    else if (Session["cs_rest_ServiceRequest"] != null && (string.Compare(Session["cs_rest_ServiceRequest"].ToString(),
                                        "deletemessage") == 0))
                    {
                        deleteMessageErrorResponse = errorMessage;
                    }
                    else
                    {
                        getMessageErrorResponse = errorMessage;
                    }
                    return false;
                }
            }
        }
        catch (Exception ex)
        {
            string errorMessage = ex.Message;
            if (Session["cs_rest_ServiceRequest"] != null && (string.Compare(Session["cs_rest_ServiceRequest"].ToString(),
                                                    "sendmessasge") == 0))
            {
                sendMessageErrorResponse = errorMessage;
            }
            else if (Session["cs_rest_ServiceRequest"] != null && (string.Compare(Session["cs_rest_ServiceRequest"].ToString(),
                                                    "createmessageindex") == 0))
            {
                createMessageIndexErrorResponse = errorMessage;
            }
            else if (Session["cs_rest_ServiceRequest"] != null && (string.Compare(Session["cs_rest_ServiceRequest"].ToString(),
                                    "getnotificationconnectiondetails") == 0))
            {
                getNotificationConnectionDetailsErrorResponse = errorMessage;
            }
            else if (Session["cs_rest_ServiceRequest"] != null && (string.Compare(Session["cs_rest_ServiceRequest"].ToString(),
                                        "deletemessage") == 0))
            {
                deleteMessageErrorResponse = errorMessage;
            }
        }
        finally
        {
            if (null != postStream)
            {
                postStream.Close();
            }
        }

        return false;
    }
    /// <summary>
    /// This method gets access token based on either client credentials mode or refresh token.
    /// </summary>
    /// <param name="type">AccessTokenType; either Client_Credential or Refresh_Token</param>
    /// <returns>true/false; true if able to get access token, else false</returns>
    private bool GetAccessToken(AccessTokenType type)
    {
        Stream postStream = null;
        StreamWriter streamWriter = null;
        FileStream fileStream = null;
        try
        {
            DateTime currentServerTime = DateTime.UtcNow.ToLocalTime();

            WebRequest accessTokenRequest = System.Net.HttpWebRequest.Create(string.Empty + this.endPoint + "/oauth/v4/token");
            accessTokenRequest.Method = "POST";

            string oauthParameters = string.Empty;
            if (type == AccessTokenType.Authorize_Credential)
            {
                oauthParameters = "client_id=" + this.apiKey.ToString() + "&client_secret=" + this.secretKey + "&code=" + this.authCode + "&grant_type=authorization_code&scope=" + this.scope;
            }
            else
            {
                oauthParameters = "grant_type=refresh_token&client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&refresh_token=" + this.refreshToken;
            }

            accessTokenRequest.ContentType = "application/x-www-form-urlencoded";

            UTF8Encoding encoding = new UTF8Encoding();

            byte[] postBytes = encoding.GetBytes(oauthParameters);
            accessTokenRequest.ContentLength = postBytes.Length;

            postStream = accessTokenRequest.GetRequestStream();
            postStream.Write(postBytes, 0, postBytes.Length);

            WebResponse accessTokenResponse = accessTokenRequest.GetResponse();

            using (StreamReader accessTokenResponseStream = new StreamReader(accessTokenResponse.GetResponseStream()))
            {
                string jsonAccessToken = accessTokenResponseStream.ReadToEnd();
                JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
                AccessTokenResponse deserializedJsonObj = (AccessTokenResponse)deserializeJsonObject.Deserialize(jsonAccessToken, typeof(AccessTokenResponse));
                DateTime accessTokenExpireTime = DateTime.Now;
                Session["Cs_DC_App1_AccessToken"] = deserializedJsonObj.access_token.ToString();
                double expiryMilliSeconds = Convert.ToDouble(deserializedJsonObj.expires_in);
                Session["refresh_token"] = deserializedJsonObj.refresh_token.ToString();
                if (expiryMilliSeconds == 0)
                {
                    Session["accessTokenExpireTime"] = accessTokenExpireTime.AddYears(100);
                }
                else
                {
                    Session["accessTokenExpireTime"] = accessTokenExpireTime.AddMilliseconds(expiryMilliSeconds);
                }
                return true;
            }
        }
        catch (WebException we)
        {
            string errorResponse = string.Empty;

            try
            {
                using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream()))
                {
                    errorResponse = sr2.ReadToEnd();
                    sr2.Close();
                }
            }
            catch
            {
                errorResponse = "Unable to get response";
            }

            getDCError = errorResponse + Environment.NewLine + we.Message;
        }
        catch (Exception ex)
        {
            getDCError = ex.Message;
        }
        finally
        {
            if (null != postStream)
            {
                postStream.Close();
            }

            if (null != streamWriter)
            {
                streamWriter.Close();
            }

            if (null != fileStream)
            {
                fileStream.Close();
            }
        }

        return false;
    }
Example #5
0
        public OAuth2Token GetAccessToken(string code, Dictionary<string, string> additional, AccessTokenType att)
        {
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add(OAUTH_GRANT_TYPE, OAUTH_GRANT_TYPE_VALUE);
            parameters.Add(OAUTH_CODE, code);
            parameters.Add(OAUTH_CLIENT_ID, _ClientId);
            if (!string.IsNullOrEmpty(_RedirectURI))
                parameters.Add(OAUTH_REDIRECT_URI, _RedirectURI);
            if (additional != null)
                foreach (var item in additional)
                    parameters.Add(item.Key, item.Value);

            string raw_token = OAuthCommonUtils.sendPostRequest(_TokenUrl, OAuthCommonUtils.getParametersString(parameters).Remove(0, 1));
            OAuth2Token token = null;
            switch (att)
            {
                case AccessTokenType.JsonDictionary:
                    token = new OAuth2Token();
                    JavaScriptSerializer s = new JavaScriptSerializer();
                    token.dictionary_token = s.Deserialize<Dictionary<string, string>>(raw_token);
                    break;
                case AccessTokenType.Raw:
                    token = new OAuth2Token();
                    token.raw_token = raw_token;
                    break;
                case AccessTokenType.Dictionary:
                    token = new OAuth2Token();
                    string[] p = raw_token.Split('&');
                    foreach (string item in p)
                    {
                        string[] key_value = item.Split('=');
                        token.dictionary_token.Add(key_value[0], key_value[1]);
                    }
                    break;
                case AccessTokenType.OAuth2Token:
                    try
                    {
                        JavaScriptSerializer serializer = new JavaScriptSerializer();
                        token = serializer.Deserialize<OAuth2Token>(raw_token);
                        token.raw_token = raw_token;
                    }
                    catch (Exception exc)
                    {
                    }
                    break;
            }

            return token;
        }
Example #6
0
        /// <summary>
        /// This function gets access token with post request
        /// </summary>
        public bool GetAccessToken(AccessTokenType type)
        {
            AccessTokenType t = type;

            var query = HttpUtility.ParseQueryString(String.Empty);

            string oauthParameters = String.Empty;

            switch (t)
            {
                case AccessTokenType.AuthorizationCode:

                    query["grant_type"] = "authorization_code";
                    query["client_id"] = apiKey;
                    query["client_secret"] = secretKey;
                    query["code"] = authCode;

                    break;

                case AccessTokenType.RefreshToken:

                    query["grant_type"] = "refresh_token";
                    query["client_id"] = apiKey;
                    query["client_secret"] = secretKey;
                    query["refresh_token"] = refreshToken;

                    break;

                case AccessTokenType.ClientCredentials:

                    query["grant_type"] = "client_credentials";
                    query["client_id"] = apiKey;
                    query["client_secret"] = secretKey;
                    query["scope"] = scope;

                    break;
            }
            oauthParameters = query.ToString();

            if (!String.IsNullOrEmpty(oauthParameters))
            {
                var apiRequest = new APIRequest("token");

                apiRequest.requireAccessToken = false;
                apiRequest.contentType = "application/x-www-form-urlencoded";
                apiRequest.accept = "application/json";
                apiRequest.setBinaryData(oauthParameters);

                if (apiService.post(apiRequest))
                {
                    accessTokenJson = apiService.apiResponse.getResponseData();
                    this.ResetTokenVariables();
                    return true;
                }
            }

            throw new Exception(apiService.errorResponse);
        }
Example #7
0
 public OAuth2Token GetAccessToken(Dictionary<string, string> additional, AccessTokenType att)
 {
     return GetAccessToken(_Code, additional, att);
 }
Example #8
0
 public OAuth2Token GetAccessToken(AccessTokenType att)
 {
     return GetAccessToken(_Code, null, att);
 }
Example #9
0
        private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTokenType tokenType)
        {
            _identityServerBuilder = new WebHostBuilder()
                                     .UseUrls(url)
                                     .UseKestrel()
                                     .UseContentRoot(Directory.GetCurrentDirectory())
                                     .UseIISIntegration()
                                     .UseUrls(url)
                                     .ConfigureServices(services =>
            {
                services.AddLogging();
                services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryApiResources(new List <ApiResource>
                {
                    new ApiResource
                    {
                        Name        = apiName,
                        Description = "My API",
                        Enabled     = true,
                        DisplayName = "test",
                        Scopes      = new List <Scope>()
                        {
                            new Scope("api"),
                            new Scope("api.readOnly"),
                            new Scope("openid"),
                            new Scope("offline_access")
                        },
                        ApiSecrets = new List <Secret>()
                        {
                            new Secret
                            {
                                Value = "secret".Sha256()
                            }
                        },
                        UserClaims = new List <string>()
                        {
                            "CustomerId", "LocationId", "UserType", "UserId"
                        }
                    },
                })
                .AddInMemoryClients(new List <Client>
                {
                    new Client
                    {
                        ClientId          = "client",
                        AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                        ClientSecrets     = new List <Secret> {
                            new Secret("secret".Sha256())
                        },
                        AllowedScopes = new List <string> {
                            apiName, "api.readOnly", "openid", "offline_access"
                        },
                        AccessTokenType     = tokenType,
                        Enabled             = true,
                        RequireClientSecret = false
                    }
                })
                .AddTestUsers(new List <TestUser>
                {
                    new TestUser
                    {
                        Username  = "******",
                        Password  = "******",
                        SubjectId = "registered|1231231",
                        Claims    = new List <Claim>
                        {
                            new Claim("CustomerId", "123"),
                            new Claim("LocationId", "321")
                        }
                    }
                });
            })
                                     .Configure(app =>
            {
                app.UseIdentityServer();
            })
                                     .Build();

            _identityServerBuilder.Start();

            _steps.VerifyIdentiryServerStarted(url);
        }
Example #10
0
 private void SetTokenType(AccessTokenType accessTokenType)
 {
     Model.AccessTokenType = (int)accessTokenType;
     TokenChanded();
 }
Example #11
0
    /// <summary>
    /// This method gets access token based on either client credentials mode or refresh token.
    /// </summary>
    /// <param name="type">AccessTokenType; either Client_Credential or Refresh_Token</param>
    /// <returns>true/false; true if able to get access token, else false</returns>
    private bool GetAccessToken(AccessTokenType type)
    {
        Stream       postStream   = null;
        StreamWriter streamWriter = null;
        FileStream   fileStream   = null;

        try
        {
            DateTime currentServerTime = DateTime.UtcNow.ToLocalTime();

            WebRequest accessTokenRequest = System.Net.HttpWebRequest.Create(string.Empty + this.endPoint + "/oauth/token");
            accessTokenRequest.Method = "POST";
            string oauthParameters = string.Empty;
            if (type == AccessTokenType.Client_Credential)
            {
                oauthParameters = "client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&grant_type=client_credentials&scope=" + this.scope;
            }
            else
            {
                oauthParameters = "grant_type=refresh_token&client_id=" + this.apiKey + "&client_secret=" + this.secretKey + "&refresh_token=" + this.refreshToken;
            }

            accessTokenRequest.ContentType = "application/x-www-form-urlencoded";
            UTF8Encoding encoding  = new UTF8Encoding();
            byte[]       postBytes = encoding.GetBytes(oauthParameters);
            accessTokenRequest.ContentLength = postBytes.Length;

            postStream = accessTokenRequest.GetRequestStream();
            postStream.Write(postBytes, 0, postBytes.Length);
            postStream.Close();

            WebResponse accessTokenResponse = accessTokenRequest.GetResponse();
            using (StreamReader accessTokenResponseStream = new StreamReader(accessTokenResponse.GetResponseStream()))
            {
                string jsonAccessToken = accessTokenResponseStream.ReadToEnd().ToString();
                JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer();
                AccessTokenResponse  deserializedJsonObj   = (AccessTokenResponse)deserializeJsonObject.Deserialize(jsonAccessToken, typeof(AccessTokenResponse));

                this.accessToken           = deserializedJsonObj.access_token.ToString();
                this.expirySeconds         = deserializedJsonObj.expires_in.ToString();
                this.refreshToken          = deserializedJsonObj.refresh_token.ToString();
                this.accessTokenExpiryTime = currentServerTime.AddSeconds(Convert.ToDouble(deserializedJsonObj.expires_in.ToString()));

                DateTime refreshExpiry = currentServerTime.AddHours(this.refreshTokenExpiresIn);

                if (deserializedJsonObj.expires_in.Equals("0"))
                {
                    int defaultAccessTokenExpiresIn = 100; // In Years
                    this.accessTokenExpiryTime = currentServerTime.AddYears(defaultAccessTokenExpiresIn);
                }

                this.refreshTokenExpiryTime = refreshExpiry.ToLongDateString() + " " + refreshExpiry.ToLongTimeString();

                fileStream   = new FileStream(Request.MapPath(this.accessTokenFilePath), FileMode.OpenOrCreate, FileAccess.Write);
                streamWriter = new StreamWriter(fileStream);

                streamWriter.WriteLine(this.accessToken);
                streamWriter.WriteLine(this.expirySeconds);
                streamWriter.WriteLine(this.refreshToken);
                streamWriter.WriteLine(this.accessTokenExpiryTime.ToString());
                streamWriter.WriteLine(this.refreshTokenExpiryTime);

                // Close and clean up the StreamReader
                accessTokenResponseStream.Close();
                return(true);
            }
        }
        catch (Exception ex)
        {
            this.DrawPanelForFailure(sendMMSPanel, ex.ToString());
            return(false);
        }
        finally
        {
            if (null != postStream)
            {
                postStream.Close();
            }

            if (null != streamWriter)
            {
                streamWriter.Close();
            }

            if (null != fileStream)
            {
                fileStream.Close();
            }
        }
    }