Repository navigation
Expand file tree
/
Copy pathAuthenticationHandler.cs
More file actions
353 lines (307 loc) · 13.1 KB
/
Copy pathAuthenticationHandler.cs
File metadata and controls
353 lines (307 loc) · 13.1 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// 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.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.AspNetCore.Http.Features.Authentication;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Authentication
{
/// <summary>
/// Base class for the per-request work performed by most authentication middleware.
/// </summary>
/// <typeparam name="TOptions">Specifies which type for of AuthenticationOptions property</typeparam>
public abstract class AuthenticationHandler<TOptions> : IAuthenticationHandler where TOptions : AuthenticationOptions
{
private Task<AuthenticateResult> _authenticateTask;
private bool _finishCalled;
protected bool SignInAccepted { get; set; }
protected bool SignOutAccepted { get; set; }
protected bool ChallengeCalled { get; set; }
protected HttpContext Context { get; private set; }
protected HttpRequest Request
{
get { return Context.Request; }
}
protected HttpResponse Response
{
get { return Context.Response; }
}
protected PathString OriginalPathBase { get; private set; }
protected PathString OriginalPath { get; private set; }
protected ILogger Logger { get; private set; }
protected UrlEncoder UrlEncoder { get; private set; }
public IAuthenticationHandler PriorHandler { get; set; }
protected string CurrentUri
{
get
{
return Request.Scheme + "://" + Request.Host + Request.PathBase + Request.Path + Request.QueryString;
}
}
protected TOptions Options { get; private set; }
/// <summary>
/// Initialize is called once per request to contextualize this instance with appropriate state.
/// </summary>
/// <param name="options">The original options passed by the application control behavior</param>
/// <param name="context">The utility object to observe the current request and response</param>
/// <param name="logger">The logging factory used to create loggers</param>
/// <param name="encoder">The <see cref="UrlEncoder"/>.</param>
/// <returns>async completion</returns>
public async Task InitializeAsync(TOptions options, HttpContext context, ILogger logger, UrlEncoder encoder)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
if (encoder == null)
{
throw new ArgumentNullException(nameof(encoder));
}
Options = options;
Context = context;
OriginalPathBase = Request.PathBase;
OriginalPath = Request.Path;
Logger = logger;
UrlEncoder = encoder;
RegisterAuthenticationHandler();
Response.OnStarting(OnStartingCallback, this);
if (ShouldHandleScheme(AuthenticationManager.AutomaticScheme, Options.AutomaticAuthenticate))
{
var result = await HandleAuthenticateOnceAsync();
if (result.Failure != null)
{
Logger.LogInformation(0, $"{Options.AuthenticationScheme} not authenticated: " + result.Failure.Message);
}
var ticket = result?.Ticket;
if (ticket?.Principal != null)
{
Context.User = SecurityHelper.MergeUserPrincipal(Context.User, ticket.Principal);
Logger.LogInformation(0, "HttpContext.User merged via AutomaticAuthentication from authenticationScheme: {scheme}.", Options.AuthenticationScheme);
}
}
}
protected string BuildRedirectUri(string targetPath)
{
return Request.Scheme + "://" + Request.Host + OriginalPathBase + targetPath;
}
private static async Task OnStartingCallback(object state)
{
var handler = (AuthenticationHandler<TOptions>)state;
await handler.FinishResponseOnce();
}
private async Task FinishResponseOnce()
{
if (!_finishCalled)
{
_finishCalled = true;
await FinishResponseAsync();
await HandleAutomaticChallengeIfNeeded();
}
}
/// <summary>
/// Hook that is called when the response about to be sent
/// </summary>
/// <returns></returns>
protected virtual Task FinishResponseAsync()
{
return Task.FromResult(0);
}
private async Task HandleAutomaticChallengeIfNeeded()
{
if (!ChallengeCalled && Options.AutomaticChallenge && Response.StatusCode == 401)
{
await HandleUnauthorizedAsync(new ChallengeContext(Options.AuthenticationScheme));
}
}
/// <summary>
/// Called once after Invoke by AuthenticationMiddleware.
/// </summary>
/// <returns>async completion</returns>
internal async Task TeardownAsync()
{
try
{
await FinishResponseOnce();
}
finally
{
UnregisterAuthenticationHandler();
}
}
/// <summary>
/// Called once by common code after initialization. If an authentication middleware responds directly to
/// specifically known paths it must override this virtual, compare the request path to it's known paths,
/// provide any response information as appropriate, and true to stop further processing.
/// </summary>
/// <returns>Returning false will cause the common code to call the next middleware in line. Returning true will
/// cause the common code to begin the async completion journey without calling the rest of the middleware
/// pipeline.</returns>
public virtual Task<bool> HandleRequestAsync()
{
return Task.FromResult(false);
}
public void GetDescriptions(DescribeSchemesContext describeContext)
{
describeContext.Accept(Options.Description.Items);
if (PriorHandler != null)
{
PriorHandler.GetDescriptions(describeContext);
}
}
public bool ShouldHandleScheme(string authenticationScheme, bool handleAutomatic)
{
return string.Equals(Options.AuthenticationScheme, authenticationScheme, StringComparison.Ordinal) ||
(handleAutomatic && string.Equals(authenticationScheme, AuthenticationManager.AutomaticScheme, StringComparison.Ordinal));
}
public async Task AuthenticateAsync(AuthenticateContext context)
{
var handled = false;
if (ShouldHandleScheme(context.AuthenticationScheme, Options.AutomaticAuthenticate))
{
// Calling Authenticate more than once should always return the original value.
var result = await HandleAuthenticateOnceAsync();
if (result?.Failure != null)
{
context.Failed(result.Failure);
}
else
{
var ticket = result?.Ticket;
if (ticket?.Principal != null)
{
context.Authenticated(ticket.Principal, ticket.Properties.Items, Options.Description.Items);
Logger.LogInformation(1, "AuthenticationScheme: {scheme} was successfully authenticated.", Options.AuthenticationScheme);
handled = true;
}
else
{
context.NotAuthenticated();
Logger.LogDebug(2, "AuthenticationScheme: {scheme} was not authenticated.", Options.AuthenticationScheme);
}
}
}
if (PriorHandler != null && !handled)
{
await PriorHandler.AuthenticateAsync(context);
}
}
protected Task<AuthenticateResult> HandleAuthenticateOnceAsync()
{
if (_authenticateTask == null)
{
_authenticateTask = HandleAuthenticateAsync();
}
return _authenticateTask;
}
protected abstract Task<AuthenticateResult> HandleAuthenticateAsync();
public async Task SignInAsync(SignInContext context)
{
if (ShouldHandleScheme(context.AuthenticationScheme, handleAutomatic: false))
{
SignInAccepted = true;
await HandleSignInAsync(context);
Logger.LogInformation(3, "AuthenticationScheme: {scheme} signed in.", Options.AuthenticationScheme);
context.Accept();
}
else if (PriorHandler != null)
{
await PriorHandler.SignInAsync(context);
}
}
protected virtual Task HandleSignInAsync(SignInContext context)
{
return Task.FromResult(0);
}
public async Task SignOutAsync(SignOutContext context)
{
if (ShouldHandleScheme(context.AuthenticationScheme, handleAutomatic: false))
{
SignOutAccepted = true;
await HandleSignOutAsync(context);
Logger.LogInformation(4, "AuthenticationScheme: {scheme} signed out.", Options.AuthenticationScheme);
context.Accept();
}
else if (PriorHandler != null)
{
await PriorHandler.SignOutAsync(context);
}
}
protected virtual Task HandleSignOutAsync(SignOutContext context)
{
return Task.FromResult(0);
}
protected virtual Task<bool> HandleForbiddenAsync(ChallengeContext context)
{
Response.StatusCode = 403;
return Task.FromResult(true);
}
/// <summary>
/// Override this method to deal with 401 challenge concerns, if an authentication scheme in question
/// deals an authentication interaction as part of it's request flow. (like adding a response header, or
/// changing the 401 result to 302 of a login page or external sign-in location.)
/// </summary>
/// <param name="context"></param>
/// <returns>True if no other handlers should be called</returns>
protected virtual Task<bool> HandleUnauthorizedAsync(ChallengeContext context)
{
Response.StatusCode = 401;
return Task.FromResult(false);
}
public async Task ChallengeAsync(ChallengeContext context)
{
ChallengeCalled = true;
var handled = false;
if (ShouldHandleScheme(context.AuthenticationScheme, Options.AutomaticChallenge))
{
switch (context.Behavior)
{
case ChallengeBehavior.Automatic:
// If there is a principal already, invoke the forbidden code path
var result = await HandleAuthenticateOnceAsync();
if (result?.Ticket?.Principal != null)
{
goto case ChallengeBehavior.Forbidden;
}
goto case ChallengeBehavior.Unauthorized;
case ChallengeBehavior.Unauthorized:
handled = await HandleUnauthorizedAsync(context);
Logger.LogInformation(5, "AuthenticationScheme: {scheme} was challenged.", Options.AuthenticationScheme);
break;
case ChallengeBehavior.Forbidden:
handled = await HandleForbiddenAsync(context);
Logger.LogInformation(6, "AuthenticationScheme: {scheme} was forbidden.", Options.AuthenticationScheme);
break;
}
context.Accept();
}
if (!handled && PriorHandler != null)
{
await PriorHandler.ChallengeAsync(context);
}
}
private void RegisterAuthenticationHandler()
{
var auth = Context.GetAuthentication();
PriorHandler = auth.Handler;
auth.Handler = this;
}
private void UnregisterAuthenticationHandler()
{
var auth = Context.GetAuthentication();
auth.Handler = PriorHandler;
}
}
}