Repository navigation
Expand file tree
/
Copy pathAuthenticationHandler.cs
More file actions
280 lines (242 loc) · 9.91 KB
/
Copy pathAuthenticationHandler.cs
File metadata and controls
280 lines (242 loc) · 9.91 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
// 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.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Authentication
{
public abstract class AuthenticationHandler<TOptions> : IAuthenticationHandler where TOptions : AuthenticationSchemeOptions, new()
{
private Task<AuthenticateResult> _authenticateTask;
public AuthenticationScheme Scheme { get; private set; }
public TOptions Options { get; private set; }
protected HttpContext Context { get; private set; }
protected HttpRequest Request
{
get { return Context.Request; }
}
protected HttpResponse Response
{
get { return Context.Response; }
}
protected PathString OriginalPath => Context.Features.Get<IAuthenticationFeature>()?.OriginalPath ?? Request.Path;
protected PathString OriginalPathBase => Context.Features.Get<IAuthenticationFeature>()?.OriginalPathBase ?? Request.PathBase;
protected ILogger Logger { get; }
protected UrlEncoder UrlEncoder { get; }
protected ISystemClock Clock { get; }
protected IOptionsSnapshot<TOptions> OptionsSnapshot { get; }
/// <summary>
/// The handler calls methods on the events which give the application control at certain points where processing is occurring.
/// If it is not provided a default instance is supplied which does nothing when the methods are called.
/// </summary>
protected virtual object Events { get; set; }
protected string CurrentUri
{
get
{
return Request.Scheme + "://" + Request.Host + Request.PathBase + Request.Path + Request.QueryString;
}
}
protected AuthenticationHandler(IOptionsSnapshot<TOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
{
Logger = logger.CreateLogger(this.GetType().FullName);
UrlEncoder = encoder;
Clock = clock;
OptionsSnapshot = options;
}
/// <summary>
/// Initialize the handler, resolve the options and validate them.
/// </summary>
/// <param name="scheme"></param>
/// <param name="context"></param>
/// <returns></returns>
public async Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
{
if (scheme == null)
{
throw new ArgumentNullException(nameof(scheme));
}
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
Scheme = scheme;
Context = context;
Options = OptionsSnapshot.Get(Scheme.Name) ?? new TOptions();
if (!Options.Initialized)
{
lock (Options.InitializeLock)
{
if (!Options.Initialized)
{
InitializeOptions();
Options.Initialized = true;
}
}
}
Options.Validate();
await InitializeEventsAsync();
await InitializeHandlerAsync();
}
/// <summary>
/// Initializes the events object, called once per request by <see cref="InitializeAsync(AuthenticationScheme, HttpContext)"/>.
/// </summary>
protected virtual async Task InitializeEventsAsync()
{
Events = Options.Events;
if (Options.EventsType != null)
{
Events = Context.RequestServices.GetRequiredService(Options.EventsType);
}
Events = Events ?? await CreateEventsAsync();
}
/// <summary>
/// Creates a new instance of the events instance.
/// </summary>
/// <returns>A new instance of the events instance.</returns>
protected virtual Task<object> CreateEventsAsync() => Task.FromResult(new object());
/// <summary>
/// Initializes the options, will be called only once by <see cref="InitializeAsync(AuthenticationScheme, HttpContext)"/>.
/// </summary>
protected virtual void InitializeOptions()
{
// REVIEW: is there a better place for this default?
Options.DisplayName = Options.DisplayName ?? Scheme.Name;
Options.ClaimsIssuer = Options.ClaimsIssuer ?? Scheme.Name;
}
/// <summary>
/// Called after options/events have been initialized for the handler to finish initializing itself.
/// </summary>
/// <returns>A task</returns>
protected virtual Task InitializeHandlerAsync()
{
return TaskCache.CompletedTask;
}
protected string BuildRedirectUri(string targetPath)
{
return Request.Scheme + "://" + Request.Host + OriginalPathBase + targetPath;
}
public async Task<AuthenticateResult> AuthenticateAsync()
{
// Calling Authenticate more than once should always return the original value.
var result = await HandleAuthenticateOnceAsync();
if (result?.Failure == null)
{
var ticket = result?.Ticket;
if (ticket?.Principal != null)
{
Logger.AuthenticationSchemeAuthenticated(Scheme.Name);
}
else
{
Logger.AuthenticationSchemeNotAuthenticated(Scheme.Name);
}
}
return result;
}
/// <summary>
/// Used to ensure HandleAuthenticateAsync is only invoked once. The subsequent calls
/// will return the same authenticate result.
/// </summary>
protected Task<AuthenticateResult> HandleAuthenticateOnceAsync()
{
if (_authenticateTask == null)
{
_authenticateTask = HandleAuthenticateAsync();
}
return _authenticateTask;
}
/// <summary>
/// Used to ensure HandleAuthenticateAsync is only invoked once safely. The subsequent
/// calls will return the same authentication result. Any exceptions will be converted
/// into a failed authentication result containing the exception.
/// </summary>
protected async Task<AuthenticateResult> HandleAuthenticateOnceSafeAsync()
{
try
{
return await HandleAuthenticateOnceAsync();
}
catch (Exception ex)
{
return AuthenticateResult.Fail(ex);
}
}
protected abstract Task<AuthenticateResult> HandleAuthenticateAsync();
public async Task SignInAsync(SignInContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
await HandleSignInAsync(context);
Logger.AuthenticationSchemeSignedIn(Scheme.Name);
}
protected virtual Task HandleSignInAsync(SignInContext context)
{
return TaskCache.CompletedTask;
}
public async Task SignOutAsync(SignOutContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
await HandleSignOutAsync(context);
Logger.AuthenticationSchemeSignedOut(Scheme.Name);
}
protected virtual Task HandleSignOutAsync(SignOutContext context)
{
return TaskCache.CompletedTask;
}
/// <summary>
/// Override this method to deal with a challenge that is forbidden.
/// </summary>
/// <param name="context"></param>
/// <returns>A Task.</returns>
protected virtual Task HandleForbiddenAsync(ChallengeContext context)
{
Response.StatusCode = 403;
return TaskCache.CompletedTask;
}
/// <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>A Task.</returns>
protected virtual Task HandleUnauthorizedAsync(ChallengeContext context)
{
Response.StatusCode = 401;
return TaskCache.CompletedTask;
}
public async Task ChallengeAsync(ChallengeContext context)
{
switch (context.Behavior)
{
case ChallengeBehavior.Automatic:
// If there is a principal already, invoke the forbidden code path
var result = await HandleAuthenticateOnceSafeAsync();
if (result?.Principal != null)
{
goto case ChallengeBehavior.Forbidden;
}
goto case ChallengeBehavior.Unauthorized;
case ChallengeBehavior.Unauthorized:
await HandleUnauthorizedAsync(context);
Logger.AuthenticationSchemeChallenged(Scheme.Name);
break;
case ChallengeBehavior.Forbidden:
await HandleForbiddenAsync(context);
Logger.AuthenticationSchemeForbidden(Scheme.Name);
break;
}
}
}
}