Skip to content

Commit bf75eaf

Browse files
committed
OAuth2 Helper to use with GitHub
Would look somewhere like the following in Windows Forms, assuming the user authorized the app. protected override void OnLoad(System.EventArgs e) { this.webBrowser1.Navigate("https://github.com/login/oauth/authorize?client_id=" + client_id + "&scope=repo,public_repo"); } public void web_Navigating(object sender, WebBrowserNavigatingEventArgs e) { string url = e.Url.ToString(); if(url.Contains("?code=")) { string[] splits = url.Split(new string[]{"?code="}, StringSplitOptions.RemoveEmptyEntries); string code = splits[1]; string token = OAuth2Helper.requestToken(client_id, client_secret, code); this.Close(); } }
1 parent 1a013e3 commit bf75eaf

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

Git.hub/Git.hub.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
<ItemGroup>
4141
<Compile Include="Branch.cs" />
4242
<Compile Include="Client.cs" />
43+
<Compile Include="OAuth2Helper.cs" />
4344
<Compile Include="Organization.cs" />
4445
<Compile Include="Properties\AssemblyInfo.cs" />
4546
<Compile Include="PullRequest.cs" />

Git.hub/OAuth2Helper.cs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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

Comments
 (0)