|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | +using RestSharp; |
| 6 | + |
| 7 | +namespace Git.hub |
| 8 | +{ |
| 9 | + class OAuth2Data |
| 10 | + { |
| 11 | + public string AccessToken { get; private set; } |
| 12 | + public string TokenType { get; private set; } |
| 13 | + } |
| 14 | + |
| 15 | + public class OAuth2Helper |
| 16 | + { |
| 17 | + /// <summary> |
| 18 | + /// Requests a Github API token, given you received a code first, i.e. user allowed that. |
| 19 | + /// |
| 20 | + /// See OAuth documentation for how to do that. |
| 21 | + /// Your App needs to be registered first. |
| 22 | + /// </summary> |
| 23 | + /// <param name="client_id">your app's client_id</param> |
| 24 | + /// <param name="client_secret">your app's secret</param> |
| 25 | + /// <param name="code">code you got from github</param> |
| 26 | + /// <returns>oauth token if successful, null otherwise</returns> |
| 27 | + public static string requestToken(string client_id, string client_secret, string code) |
| 28 | + { |
| 29 | + // Not on api.github.com |
| 30 | + var client = new RestClient("https://github.com"); |
| 31 | + |
| 32 | + var request = new RestRequest("/login/oauth/access_token"); |
| 33 | + request.RequestFormat = DataFormat.Json; |
| 34 | + request.AddParameter("client_id", client_id); |
| 35 | + request.AddParameter("client_secret", client_secret); |
| 36 | + request.AddParameter("code", code); |
| 37 | + |
| 38 | + var response = client.Post<OAuth2Data>(request); |
| 39 | + if (response.Data != null) |
| 40 | + return response.Data.AccessToken; |
| 41 | + return null; |
| 42 | + } |
| 43 | + } |
| 44 | +} |
0 commit comments