Skip to content

Instantly share code, notes, and snippets.

@abrudtkuhl
Created June 26, 2012 14:34
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save abrudtkuhl/2996120 to your computer and use it in GitHub Desktop.
Save abrudtkuhl/2996120 to your computer and use it in GitHub Desktop.
Github OAuth callback for ASP.Net MVC. Set yourapp.com/github/callback as the OAuth callback URL when you setup your application. If the users chooses to grant you permission, this controller/action get called to complete the transaction. See http://devel
public class GithubController : Controller
{
/// <summary>
/// Github OAuth Callback
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
public JsonResult callback(string code)
{
var clientId = "[insert yours]";
var clientSecret = "[insert yours]";
var client = new RestClient("https://github.com/");
var request = new RestRequest("login/oauth/access_token", Method.POST);
request.AddParameter("client_id", clientId);
request.AddParameter("client_secret", clientSecret);
request.AddParameter("code", code);
RestResponse<GithubOauthResponse> response = client.Execute<GithubOauthResponse>(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
// we're in...
var apiClient = new RestClient("https://api.github.com");
var apiRequest = new RestRequest("/user?access_token=" + response.Data.AccessToken, Method.GET);
apiClient.ExecuteAsync<GithubProfile>(apiRequest, apiResponse => {
// do something async
var githubUser = apiResponse.Data.Login;
});
return Json(new { Success = true, Message = "Successfully logged in with Github", Login = githubUser });
}
return Json(new { Success = false, Message = "Oops, something happened" });
}
}
public class GithubOauthResponse {
public string TokenType { get; set; }
public string AccessToken { get; set; }
}
public class GithubProfile
{
public string Login { get; set; }
public string Id { get; set; }
public string AvatarUrl { get; set; }
public string GravatarId { get; set; }
public string Url { get; set; }
public string Name { get; set; }
public string Company { get; set; }
public string Blog { get; set; }
public string Location { get; set; }
public string Email { get; set; }
public bool Hireable { get; set; }
public string Bio { get; set; }
public int PublicRepos { get; set; }
public int PublicGists { get; set; }
public int Followers { get; set; }
public int Following { get; set; }
public string HtmlUrl { get; set; }
public string CreatedAt { get; set; }
public string Type { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment