public bool Authorize(GoogleAccount account) { DictionaryDataStore dataStore = new DictionaryDataStore(); if (account != null) { account.LoadDataStore(dataStore: ref dataStore); } try { UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( clientSecrets: GoogleSecrets.ToClientSecrets(Secrets), scopes: GoogleScopes.ToStrings(Scopes), user: "******", taskCancellationToken: CancellationToken.None, dataStore: dataStore ).Result; Accounts.Add(GoogleAccount.SaveAccount(broker: this, credential: credential, dataStore: dataStore)); return(true); } catch (TokenResponseException ex) { if (ex.Message.Contains("invalid_grant")) { return(account.Reauthenticate()); } else { Log.Error(ex); } return(false); } }
public UserCredential Authorize(string googleUser) { return(GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleSecrets.ToClientSecrets(Secrets), GoogleScopes.ToStrings(Scopes), googleUser, System.Threading.CancellationToken.None, new FileDataStore(AppName) ).Result); }
public static async Task <string> GetRefreshToken(string clientId, string clientSecret, string appName, GoogleScopes googleScope) { // Generates state and PKCE values. var state = RandomDataBase64Url(32); var codeVerifier = RandomDataBase64Url(32); var codeChallenge = Base64UrlencodeNoPadding(Sha256(codeVerifier)); const string CodeChallengeMethod = "S256"; // Creates a redirect URI using an available port on the loopback address. var redirectUri = $"http://{IPAddress.Loopback}:{GetRandomUnusedPort()}/"; // Creates an HttpListener to listen for requests on that redirect URI. var http = new HttpListener(); http.Prefixes.Add(redirectUri); http.Start(); var scope = GoogleScopes[googleScope]; // Creates the OAuth 2.0 authorization request. var authorizationRequest = $"{AuthorizationEndpoint}?response_type=code" + $"&scope=openid%20{scope}" + $"&redirect_uri={System.Uri.EscapeDataString(redirectUri)}" + $"&client_id={clientId}" + $"&state={state}" + $"&code_challenge={codeChallenge}" + $"&code_challenge_method={CodeChallengeMethod}"; // Opens request in the browser. System.Diagnostics.Process.Start(authorizationRequest); // Waits for the OAuth authorization response. var context = await http.GetContextAsync(); // Sends an HTTP response to the browser. var response = context.Response; var responseString = $"<html><head><meta http-equiv=\'refresh\' content=\'10;url=https://google.com\'></head><body>Please return to the {appName}.</body></html>"; var buffer = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; var responseOutput = response.OutputStream; await responseOutput.WriteAsync(buffer, 0, buffer.Length).ContinueWith((task) => { responseOutput.Close(); http.Stop(); }); // Checks for errors. if (context.Request.QueryString.Get("error") != null) { throw new GoogleException($"OAuth authorization error: {context.Request.QueryString.Get("error")}."); } if (context.Request.QueryString.Get("code") == null || context.Request.QueryString.Get("state") == null) { throw new GoogleException("Malformed authorization response. " + context.Request.QueryString); } // extracts the code var code = context.Request.QueryString.Get("code"); var incomingState = context.Request.QueryString.Get("state"); // Compares the receieved state to the expected value, to ensure that // this app made the request which resulted in authorization. if (incomingState != state) { throw new GoogleException($"Received request with invalid state ({incomingState})"); } // Starts the code exchange at the Token Endpoint. return(await PerformCodeExchange(clientId, clientSecret, code, codeVerifier, redirectUri)); }