Skip to content

Instantly share code, notes, and snippets.

@igorkulman
Last active August 29, 2015 14:24
Show Gist options
  • Save igorkulman/65a406f7f3cff48be3c5 to your computer and use it in GitHub Desktop.
Save igorkulman/65a406f7f3cff48be3c5 to your computer and use it in GitHub Desktop.
internal static string GoogleAppId = "your google app id";
internal static string GoogleAppSecret = "your google app secret";
internal static Uri GoogleStartUri = new Uri("https://accounts.google.com/o/oauth2/auth?client_id=" + Uri.EscapeDataString(GoogleAppId) + "&redirect_uri=" + Uri.EscapeDataString("urn:ietf:wg:oauth:2.0:oob") + "&response_type=code&scope=" + Uri.EscapeDataString("profile https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.me email"));
internal static Uri GoogleEndUri = new Uri("https://accounts.google.com/o/oauth2/approval?");
private string GetGoogleSuccessCode(string data)
{
if (string.IsNullOrEmpty(data)) return null;
var parts = data.Split('=');
for (int i = 0; i < parts.Length; ++i)
{
if (parts[i] == "Success code")
{
return parts[i + 1];
}
}
return null;
}
public async Task<string> GetToken(string code)
{
var client = new HttpClient();
var auth = await client.PostAsync("https://accounts.google.com/o/oauth2/token", new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("code", code),
new KeyValuePair<string, string>("client_id",Config.GoogleAppId),
new KeyValuePair<string, string>("client_secret",Config.GoogleAppSecret),
new KeyValuePair<string, string>("grant_type","authorization_code"),
new KeyValuePair<string, string>("redirect_uri","urn:ietf:wg:oauth:2.0:oob"),
}));
var data = await auth.Content.ReadAsStringAsync();
Debug.WriteLine(data);
var j = JToken.Parse(data);
var token = j.SelectToken("access_token");
return token;
}
#if WINDOWS_APP
var auth = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.UseTitle, Config.GoogleStartUri, Config.GoogleEndUri);
Debug.WriteLine(auth.ResponseData);
var successCode = GetGoogleSuccessCode(auth.ResponseData);
var token = GetToken(successCode);
//do something with the authentication token
#else
WebAuthenticationBroker.AuthenticateAndContinue(Config.GoogleStartUri, Config.GoogleEndUri, null, WebAuthenticationOptions.UseTitle);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment