protected void Authenticate() { var code = Request["code"]; if (String.IsNullOrEmpty(code)) { // See if we're authed AuthorizationCodeWebApp.AuthResult AuthResult = LeadsUtil.GetAuthResult(hf_uri.Value, hf_user_id.Value); if (AuthResult != null) { // User is authenticated.. if (AuthResult.RedirectUri == null) { lbl_title.Text = "You are now authenticated with Google Mail API.. you can close this window and return to DataGeek."; } // User is not authenticated, start the authentication process.. else { // Redirect the user to the authorization server. Response.Redirect(AuthResult.RedirectUri); } } else { Util.PageMessageAlertify(this, "Error getting auth result from Google, please try reloading this page."); } } else // When returning with a code to complete in-process authentication { IAuthorizationCodeFlow flow = LeadsUtil.GetAuthCodeFlow(); if (flow != null) { var token = flow.ExchangeCodeForTokenAsync(hf_user_id.Value, code, hf_uri.Value.Substring(0, hf_uri.Value.IndexOf("?")), CancellationToken.None).Result; // Extract the right state. try { var oauthState = AuthWebUtility.ExtracRedirectFromState(flow.DataStore, hf_user_id.Value, Request["state"]).Result; Response.Redirect(oauthState); } catch { Response.Redirect("authwithgmapi.aspx"); } } else { Util.PageMessageAlertify(this, "Error getting token from Google, please try reloading this page."); } } }