Created
January 22, 2014 20:25
-
-
Save nigel-sampson/8566723 to your computer and use it in GitHub Desktop.
OAuth
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
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