public static bool Authorize() { Console.WriteLine("Authendication needed!"); Console.WriteLine("Go to the following url in your browser:"); Console.WriteLine(AuthFlow.CreateAuthorizationCodeRequest(Constants.URI_GDRIVE_REDIRECT).Build().ToString()); Console.WriteLine(); Console.WriteLine("Enter verification code: "); string token = Console.ReadLine(); try { TokenResponse response = AuthFlow.ExchangeCodeForTokenAsync(Environment.UserName, token, Constants.URI_GDRIVE_REDIRECT, new CancellationToken()).Result; AuthFlow.DataStore.StoreAsync(Environment.UserName, response).Wait(); return(true); } catch (Exception ex) { string errorMessage = ex.Message; Match match = (new Regex(Constants.REGEX_AUTH_ERROR)).Match(ex.Message); if (match.Success) { errorMessage = string.Format("{0} ({1})", match.Groups["Description"], match.Groups["Error"]); } Console.WriteLine(string.Format("Authendication Failed! {0}\nPlease try again...", errorMessage)); } return(false); }
public async Task <UserCredential> GetToken(string state, string code) { if (code != null) { var user = state.Substring(43); var token = await flow.ExchangeCodeForTokenAsync(user, code, redirectURI, CancellationToken.None); UserCredential userCredential = new UserCredential(flow, user, token); return(userCredential); } return(null); }
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."); } } }