Last active
October 19, 2015 07:55
-
-
Save LindaLawton/3286577bfa97ae703dd7 to your computer and use it in GitHub Desktop.
exchanges the authetncation code for the refreshtoken and access token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TokenResponse | |
{ | |
public string access_token { get; set; } | |
public string token_type { get; set; } | |
public string expires_in { get; set; } | |
public string refresh_token { get; set; } | |
} | |
/// <summary> | |
/// exchanges the authetncation code for the refreshtoken and access token | |
/// </summary> | |
/// <param name="code"></param> | |
/// <returns></returns> | |
public static string exchangeCode(string code) | |
{ | |
string url = "https://accounts.google.com/o/oauth2/token"; | |
string postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code", code, Properties.Resources.clientId, Properties.Resources.secret); | |
// Create a request using a URL that can receive a post. | |
WebRequest request = WebRequest.Create(url); | |
// Set the Method property of the request to POST. | |
request.Method = "POST"; | |
byte[] byteArray = Encoding.UTF8.GetBytes(postData); | |
// Set the ContentType property of the WebRequest. | |
request.ContentType = "application/x-www-form-urlencoded"; | |
// Set the ContentLength property of the WebRequest. | |
request.ContentLength = byteArray.Length; | |
// Get the request stream. | |
Stream dataStream = request.GetRequestStream(); | |
// Write the data to the request stream. | |
dataStream.Write(byteArray, 0, byteArray.Length); | |
// Close the Stream object. | |
dataStream.Close(); | |
// Get the response. | |
WebResponse response = request.GetResponse(); | |
// Display the status. | |
Console.WriteLine(((HttpWebResponse)response).StatusDescription); | |
// Get the stream containing content returned by the server. | |
dataStream = response.GetResponseStream(); | |
// Open the stream using a StreamReader for easy access. | |
StreamReader reader = new StreamReader(dataStream); | |
// Read the content. | |
string responseFromServer = reader.ReadToEnd(); | |
TokenResponse tmp = JsonConvert.DeserializeObject<TokenResponse>(responseFromServer); | |
// Display the content. | |
Console.WriteLine(responseFromServer); | |
// Clean up the streams. | |
reader.Close(); | |
dataStream.Close(); | |
response.Close(); | |
return tmp.refresh_token; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment