Repository navigation
Expand file tree
/
Copy pathOAuthAuthenticationHandler.cs
More file actions
284 lines (237 loc) · 10.5 KB
/
Copy pathOAuthAuthenticationHandler.cs
File metadata and controls
284 lines (237 loc) · 10.5 KB
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Threading.Tasks;
using Microsoft.AspNet.Authentication.DataHandler.Encoder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Http.Extensions;
using Microsoft.AspNet.Http.Features.Authentication;
using Microsoft.AspNet.WebUtilities;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Logging;
using Newtonsoft.Json.Linq;
namespace Microsoft.AspNet.Authentication.OAuth
{
public class OAuthAuthenticationHandler<TOptions, TNotifications> : AuthenticationHandler<TOptions>
where TOptions : OAuthAuthenticationOptions<TNotifications>
where TNotifications : IOAuthAuthenticationNotifications
{
private static readonly RandomNumberGenerator CryptoRandom = RandomNumberGenerator.Create();
public OAuthAuthenticationHandler(HttpClient backchannel)
{
Backchannel = backchannel;
}
protected HttpClient Backchannel { get; private set; }
public override async Task<bool> InvokeAsync()
{
if (Options.CallbackPath.HasValue && Options.CallbackPath == Request.Path)
{
return await InvokeReturnPathAsync();
}
return false;
}
public async Task<bool> InvokeReturnPathAsync()
{
var ticket = await AuthenticateAsync();
if (ticket == null)
{
Logger.LogWarning("Invalid return state, unable to redirect.");
Response.StatusCode = 500;
return true;
}
var context = new OAuthReturnEndpointContext(Context, ticket)
{
SignInScheme = Options.SignInScheme,
RedirectUri = ticket.Properties.RedirectUri,
};
ticket.Properties.RedirectUri = null;
await Options.Notifications.ReturnEndpoint(context);
if (context.SignInScheme != null && context.Principal != null)
{
await Context.Authentication.SignInAsync(context.SignInScheme, context.Principal, context.Properties);
}
if (!context.IsRequestCompleted && context.RedirectUri != null)
{
if (context.Principal == null)
{
// add a redirect hint that sign-in failed in some way
context.RedirectUri = QueryHelpers.AddQueryString(context.RedirectUri, "error", "access_denied");
}
Response.Redirect(context.RedirectUri);
context.RequestCompleted();
}
return context.IsRequestCompleted;
}
public override async Task<AuthenticationTicket> AuthenticateAsync()
{
AuthenticationProperties properties = null;
try
{
var query = Request.Query;
// TODO: Is this a standard error returned by servers?
var value = query.Get("error");
if (!string.IsNullOrEmpty(value))
{
Logger.LogVerbose("Remote server returned an error: " + Request.QueryString);
// TODO: Fail request rather than passing through?
return null;
}
var code = query.Get("code");
var state = query.Get("state");
properties = Options.StateDataFormat.Unprotect(state);
if (properties == null)
{
return null;
}
// OAuth2 10.12 CSRF
if (!ValidateCorrelationId(properties))
{
return new AuthenticationTicket(properties, Options.AuthenticationScheme);
}
if (string.IsNullOrEmpty(code))
{
// Null if the remote server returns an error.
return new AuthenticationTicket(properties, Options.AuthenticationScheme);
}
var tokens = await ExchangeCodeAsync(code, BuildRedirectUri(Options.CallbackPath));
if (string.IsNullOrWhiteSpace(tokens.AccessToken))
{
Logger.LogWarning("Access token was not found");
return new AuthenticationTicket(properties, Options.AuthenticationScheme);
}
return await GetUserInformationAsync(properties, tokens);
}
catch (Exception ex)
{
Logger.LogError("Authentication failed", ex);
return new AuthenticationTicket(properties, Options.AuthenticationScheme);
}
}
protected virtual async Task<TokenResponse> ExchangeCodeAsync(string code, string redirectUri)
{
var tokenRequestParameters = new Dictionary<string, string>()
{
{ "client_id", Options.ClientId },
{ "redirect_uri", redirectUri },
{ "client_secret", Options.ClientSecret },
{ "code", code },
{ "grant_type", "authorization_code" },
};
var requestContent = new FormUrlEncodedContent(tokenRequestParameters);
var requestMessage = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint);
requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
requestMessage.Content = requestContent;
var response = await Backchannel.SendAsync(requestMessage, Context.RequestAborted);
response.EnsureSuccessStatusCode();
var oauthTokenResponse = await response.Content.ReadAsStringAsync();
var oauth2Token = JObject.Parse(oauthTokenResponse);
return new TokenResponse(oauth2Token);
}
protected virtual async Task<AuthenticationTicket> GetUserInformationAsync(AuthenticationProperties properties, TokenResponse tokens)
{
var context = new OAuthGetUserInformationContext(Context, Options, Backchannel, tokens)
{
Properties = properties,
};
await Options.Notifications.GetUserInformationAsync(context);
return new AuthenticationTicket(context.Principal, context.Properties, Options.AuthenticationScheme);
}
protected override Task<bool> HandleUnauthorizedAsync([NotNull] ChallengeContext context)
{
var properties = new AuthenticationProperties(context.Properties);
if (string.IsNullOrEmpty(properties.RedirectUri))
{
properties.RedirectUri = CurrentUri;
}
// OAuth2 10.12 CSRF
GenerateCorrelationId(properties);
var authorizationEndpoint = BuildChallengeUrl(properties, BuildRedirectUri(Options.CallbackPath));
var redirectContext = new OAuthApplyRedirectContext(
Context, Options,
properties, authorizationEndpoint);
Options.Notifications.ApplyRedirect(redirectContext);
return Task.FromResult(true);
}
protected override Task HandleSignOutAsync(SignOutContext context)
{
throw new NotSupportedException();
}
protected override Task HandleSignInAsync(SignInContext context)
{
throw new NotSupportedException();
}
protected override Task<bool> HandleForbiddenAsync(ChallengeContext context)
{
throw new NotSupportedException();
}
protected virtual string BuildChallengeUrl(AuthenticationProperties properties, string redirectUri)
{
var scope = FormatScope();
var state = Options.StateDataFormat.Protect(properties);
var queryBuilder = new QueryBuilder()
{
{ "client_id", Options.ClientId },
{ "scope", scope },
{ "response_type", "code" },
{ "redirect_uri", redirectUri },
{ "state", state },
};
return Options.AuthorizationEndpoint + queryBuilder.ToString();
}
protected virtual string FormatScope()
{
// OAuth2 3.3 space separated
return string.Join(" ", Options.Scope);
}
protected void GenerateCorrelationId([NotNull] AuthenticationProperties properties)
{
var correlationKey = Constants.CorrelationPrefix + Options.AuthenticationScheme;
var nonceBytes = new byte[32];
CryptoRandom.GetBytes(nonceBytes);
var correlationId = TextEncodings.Base64Url.Encode(nonceBytes);
var cookieOptions = new CookieOptions
{
HttpOnly = true,
Secure = Request.IsHttps
};
properties.Items[correlationKey] = correlationId;
Response.Cookies.Append(correlationKey, correlationId, cookieOptions);
}
protected bool ValidateCorrelationId([NotNull] AuthenticationProperties properties)
{
var correlationKey = Constants.CorrelationPrefix + Options.AuthenticationScheme;
var correlationCookie = Request.Cookies[correlationKey];
if (string.IsNullOrWhiteSpace(correlationCookie))
{
Logger.LogWarning("{0} cookie not found.", correlationKey);
return false;
}
var cookieOptions = new CookieOptions
{
HttpOnly = true,
Secure = Request.IsHttps
};
Response.Cookies.Delete(correlationKey, cookieOptions);
string correlationExtra;
if (!properties.Items.TryGetValue(
correlationKey,
out correlationExtra))
{
Logger.LogWarning("{0} state property not found.", correlationKey);
return false;
}
properties.Items.Remove(correlationKey);
if (!string.Equals(correlationCookie, correlationExtra, StringComparison.Ordinal))
{
Logger.LogWarning("{0} correlation cookie and state property mismatch.", correlationKey);
return false;
}
return true;
}
}
}