Skip to content

Instantly share code, notes, and snippets.

@nigel-sampson
Created January 22, 2014 20:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nigel-sampson/8566723 to your computer and use it in GitHub Desktop.
Save nigel-sampson/8566723 to your computer and use it in GitHub Desktop.
OAuth
public class OAuthCredentialsStore : ICredentialStore
{
private const string ClientId = "<redacted>";
private const string ClientSecret = "<redacted>";
private readonly IGitHubClient _gitHubClient;
public OAuthCredentialsStore()
{
_gitHubClient = new GitHubClient(new ProductHeaderValue("HubBug", "0.0.0.1"))
{
Credentials = Credentials.Anonymous
};
}
public async Task<Credentials> GetCredentials()
{
var state = Guid.NewGuid().ToString("N");
const string redirectUri = "http://compiledexperience.com/windows-apps/hub-bug/authenticate";
var uri = String.Format("https://github.com/login/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}&state={3}",
ClientId, redirectUri, "user,repo", state);
var result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None,
new Uri(uri), new Uri(redirectUri));
if (result.ResponseStatus != WebAuthenticationStatus.Success)
return Credentials.Anonymous;
var responseUri = new Uri(result.ResponseData);
var responseParameters = responseUri.ParseQueryString();
if (state != responseParameters["state"])
return Credentials.Anonymous;
var contentParams = new Dictionary<string, string>
{
{"client_id", ClientId },
{"client_secret", ClientSecret },
{"code", responseParameters["code"] },
{"state", state }
};
var content = String.Join("&", contentParams.Select(p => String.Format("{0}={1}", p.Key, p.Value)));
var response = await _gitHubClient.Connection.PostAsync<OAuthToken>(new Uri("https://github.com/login/oauth/access_token", UriKind.Absolute), content, "application/json", "application/x-www-form-urlencoded");
return new Credentials(response.BodyAsObject.AccessToken);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment