-
-
Save codeimpossible/3756551 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
This file contains 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 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