-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathGitHubOAuth.cs
202 lines (174 loc) · 7.38 KB
/
GitHubOAuth.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
using System;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Web;
namespace OAuthConsole
{
static class GitHubOAuth
{
internal class Result
{
internal string Token;
internal string Error;
}
internal static async Task<Result> GetToken(
string clientId,
string clientSecret,
string state,
string redirectUri,
string htmlResponseToShowInBrowser)
{
// Creates an HttpListener to listen for requests on that redirect URI.
var http = new HttpListener();
http.Prefixes.Add(redirectUri);
Debug("Listening on " + redirectUri);
http.Start();
// Creates the OAuth 2.0 authorization request.
RequestIdentity.Request(clientId, state, redirectUri);
// Waits for the OAuth authorization response.
var context = await http.GetContextAsync();
// Brings the Console to Focus.
ConsoleHack.BringConsoleToFront();
// Sends an HTTP response to the browser.
var response = context.Response;
var buffer = System.Text.Encoding.UTF8.GetBytes(htmlResponseToShowInBrowser);
response.ContentLength64 = buffer.Length;
var responseOutput = response.OutputStream;
Task responseTask = responseOutput.WriteAsync(
buffer, 0, buffer.Length).ContinueWith((task) =>
{
responseOutput.Close();
http.Stop();
Debug("HTTP server stopped.");
});
// Checks for errors.
if (context.Request.QueryString.Get("error") != null)
{
return new Result()
{
Token = null,
Error = string.Format("OAuth authorization error: {0}.",
context.Request.QueryString.Get("error"))
};
}
if (context.Request.QueryString.Get("code") == null
|| context.Request.QueryString.Get("state") == null)
{
return new Result()
{
Token = null,
Error = "Malformed authorization response. " + context.Request.QueryString
};
}
// extracts the code
var code = context.Request.QueryString.Get("code");
var incoming_state = context.Request.QueryString.Get("state");
// Compares the receieved state to the expected value, to ensure that
// this app made the request which resulted in authorization.
if (incoming_state != state)
{
return new Result()
{
Token = null,
Error = string.Format(
"Received request with invalid state ({0})", incoming_state)
};
}
Debug("Authorization code: " + code);
return new Result()
{
Token = await RequestToken.Get(clientId, clientSecret, code, redirectUri, state),
Error = null
};
}
static class RequestIdentity
{
const string AuthorizationEndpoint = "http://github.com/login/oauth/authorize";
internal static void Request(string clientId, string state, string redirectUri)
{
string authorizationRequest = string.Format(
"{0}?client_id={1}" +
"&redirect_uri={2}" +
"&scope=" +
"&state={3}" +
"&allow_signup=true",
AuthorizationEndpoint,
clientId,
System.Uri.EscapeDataString(redirectUri),
state);
// Opens request in the browser.
System.Diagnostics.Process.Start(authorizationRequest);
}
}
static class RequestToken
{
const string TokenEndpoint = "https://github.com/login/oauth/access_token";
static internal async Task<string> Get(
string clientId,
string clientSecret,
string code,
string redirectURI,
string state)
{
Debug("Exchanging code for tokens...");
// builds the request
string tokenRequestBody = string.Format(
"client_id={0}&client_secret={1}&code={2}&redirect_uri={3}&state={4}",
clientId,
clientSecret,
code,
System.Uri.EscapeDataString(redirectURI),
state);
// sends the request
HttpWebRequest tokenRequest = (HttpWebRequest)WebRequest.Create(TokenEndpoint);
tokenRequest.Method = "POST";
tokenRequest.ContentType = "application/x-www-form-urlencoded";
tokenRequest.Accept = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
byte[] _byteVersion = Encoding.ASCII.GetBytes(tokenRequestBody);
tokenRequest.ContentLength = _byteVersion.Length;
Stream stream = tokenRequest.GetRequestStream();
await stream.WriteAsync(_byteVersion, 0, _byteVersion.Length);
stream.Close();
try
{
// gets the response
WebResponse tokenResponse = await tokenRequest.GetResponseAsync();
using (StreamReader reader = new StreamReader(tokenResponse.GetResponseStream()))
{
// reads response body
string responseText = await reader.ReadToEndAsync();
Console.WriteLine(responseText);
// By default, the response takes the following form:
// access_token=xxxxxxxxxxxxxxxxxx&token_type=bearer
string accessToken = HttpUtility.ParseQueryString(responseText)[0];
return accessToken;
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
var response = ex.Response as HttpWebResponse;
if (response == null)
return string.Empty;
Debug("HTTP: " + response.StatusCode);
using (StreamReader reader = new StreamReader(
response.GetResponseStream()))
{
// reads response body
string responseText = reader.ReadToEnd();
Console.WriteLine(responseText);
}
}
return string.Empty;
}
}
}
static void Debug(string s)
{
Console.WriteLine(s);
}
}
}