private static async Task <OAuthToken> PerformCodeExchange(string code, string codeVerifier, string redirectURI, string clientId, string clientSecret) { //Console.WriteLine("Exchanging code for tokens..."); // builds the request string tokenRequestURI = "https://www.googleapis.com/oauth2/v4/token"; string tokenRequestBody = string.Format("code={0}&redirect_uri={1}&client_id={2}&code_verifier={3}&client_secret={4}&scope=&grant_type=authorization_code", code, Uri.EscapeDataString(redirectURI), clientId, codeVerifier, clientSecret ); // sends the request HttpWebRequest tokenRequest = (HttpWebRequest)WebRequest.Create(tokenRequestURI); tokenRequest.Method = "POST"; tokenRequest.ContentType = "application/x-www-form-urlencoded"; tokenRequest.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; byte[] byteVersion = Encoding.ASCII.GetBytes(tokenRequestBody); tokenRequest.ContentLength = byteVersion.Length; Stream stream = tokenRequest.GetRequestStream(); await stream.WriteAsync(byteVersion, 0, byteVersion.Length); stream.Close(); // gets the response WebResponse tokenResponse = await tokenRequest.GetResponseAsync(); using (StreamReader reader = new StreamReader(tokenResponse.GetResponseStream())) { // reads response body string responseText = await reader.ReadToEndAsync(); //Console.WriteLine(responseText); // converts to dictionary Dictionary <string, string> tokenEndpointDecoded = serializer.DeserializeObject <Dictionary <string, string> >(responseText); OAuthToken token = new OAuthToken(); token.accessToken = tokenEndpointDecoded["access_token"]; token.expiresIn = int.Parse(tokenEndpointDecoded["expires_in"]); token.refreshToken = tokenEndpointDecoded["refresh_token"]; token.scope = tokenEndpointDecoded["scope"]; token.tokenType = tokenEndpointDecoded["token_type"]; token.idToken = tokenEndpointDecoded["id_token"]; return(token); //UserinfoCall(access_token); } }
protected virtual T DeserializeObject <T>(string data) { return(serializer.DeserializeObject <T>(data)); }