forked from openiddict/openiddict-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenIddictServerAspNetCoreHandlers.Authentication.cs
More file actions
370 lines (319 loc) · 17.7 KB
/
OpenIddictServerAspNetCoreHandlers.Authentication.cs
File metadata and controls
370 lines (319 loc) · 17.7 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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using System.Collections.Immutable;
using System.Text;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
namespace OpenIddict.Server.AspNetCore;
public static partial class OpenIddictServerAspNetCoreHandlers
{
public static class Authentication
{
public static ImmutableArray<OpenIddictServerHandlerDescriptor> DefaultHandlers { get; } =
[
/*
* Authorization request extraction:
*/
ExtractGetOrPostRequest<ExtractAuthorizationRequestContext>.Descriptor,
/*
* Authorization request handling:
*/
EnablePassthroughMode<HandleAuthorizationRequestContext, RequireAuthorizationEndpointPassthroughEnabled>.Descriptor,
/*
* Authorization response processing:
*/
AttachHttpResponseCode<ApplyAuthorizationResponseContext>.Descriptor,
AttachCacheControlHeader<ApplyAuthorizationResponseContext>.Descriptor,
ProcessSelfRedirection.Descriptor,
ProcessFormPostResponse.Descriptor,
ProcessQueryResponse.Descriptor,
ProcessFragmentResponse.Descriptor,
ProcessPassthroughErrorResponse<ApplyAuthorizationResponseContext, RequireAuthorizationEndpointPassthroughEnabled>.Descriptor,
ProcessStatusCodePagesErrorResponse<ApplyAuthorizationResponseContext>.Descriptor,
ProcessLocalErrorResponse<ApplyAuthorizationResponseContext>.Descriptor,
/*
* Pushed authorization request extraction:
*/
ExtractPostRequest<ExtractPushedAuthorizationRequestContext>.Descriptor,
ValidateClientAuthenticationMethod<ExtractPushedAuthorizationRequestContext>.Descriptor,
ExtractBasicAuthenticationCredentials<ExtractPushedAuthorizationRequestContext>.Descriptor,
/*
* Pushed authorization response processing:
*/
AttachHttpResponseCode<ApplyPushedAuthorizationResponseContext>.Descriptor,
AttachCacheControlHeader<ApplyPushedAuthorizationResponseContext>.Descriptor,
AttachWwwAuthenticateHeader<ApplyPushedAuthorizationResponseContext>.Descriptor,
ProcessJsonResponse<ApplyPushedAuthorizationResponseContext>.Descriptor
];
/// <summary>
/// Contains the logic responsible for processing authorization responses requiring a self-redirection.
/// Note: this handler is not used when the OpenID Connect request is not initially handled by ASP.NET Core.
/// </summary>
public sealed class ProcessSelfRedirection : IOpenIddictServerHandler<ApplyAuthorizationResponseContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ApplyAuthorizationResponseContext>()
.AddFilter<RequireHttpRequest>()
.UseSingletonHandler<ProcessSelfRedirection>()
.SetOrder(250_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ApplyAuthorizationResponseContext context)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (context is not { BaseUri.IsAbsoluteUri: true, RequestUri.IsAbsoluteUri: true })
{
throw new InvalidOperationException(SR.GetResourceString(SR.ID0127));
}
if (string.IsNullOrEmpty(context.Response.RequestUri))
{
return default;
}
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
#if SUPPORTS_MULTIPLE_VALUES_IN_QUERYHELPERS
var location = QueryHelpers.AddQueryString(context.RequestUri.GetLeftPart(UriPartial.Path),
from parameter in context.Response.GetParameters()
let values = (ImmutableArray<string?>?) parameter.Value
where values is not null
from value in values.GetValueOrDefault()
where !string.IsNullOrEmpty(value)
select KeyValuePair.Create(parameter.Key, value));
#else
var location = context.RequestUri.GetLeftPart(UriPartial.Path);
foreach (var (key, value) in
from parameter in context.Response.GetParameters()
let values = (ImmutableArray<string?>?) parameter.Value
where values is not null
from value in values.GetValueOrDefault()
where !string.IsNullOrEmpty(value)
select (parameter.Key, Value: value))
{
location = QueryHelpers.AddQueryString(location, key, value);
}
#endif
response.Redirect(location);
context.HandleRequest();
return default;
}
}
/// <summary>
/// Contains the logic responsible for processing authorization responses using the form_post response mode.
/// Note: this handler is not used when the OpenID Connect request is not initially handled by ASP.NET Core.
/// </summary>
public sealed class ProcessFormPostResponse : IOpenIddictServerHandler<ApplyAuthorizationResponseContext>
{
private readonly HtmlEncoder _encoder;
public ProcessFormPostResponse(HtmlEncoder encoder)
=> _encoder = encoder;
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ApplyAuthorizationResponseContext>()
.AddFilter<RequireHttpRequest>()
.UseSingletonHandler<ProcessFormPostResponse>()
.SetOrder(ProcessSelfRedirection.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public async ValueTask HandleAsync(ApplyAuthorizationResponseContext context)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
if (string.IsNullOrEmpty(context.RedirectUri) ||
!string.Equals(context.ResponseMode, ResponseModes.FormPost, StringComparison.Ordinal))
{
return;
}
context.Logger.LogInformation(SR.GetResourceString(SR.ID6147), context.RedirectUri, context.Response);
using var buffer = new MemoryStream();
using var writer = new StreamWriter(buffer);
writer.WriteLine("<!doctype html>");
writer.WriteLine("<html>");
writer.WriteLine("<body>");
// While the redirect_uri parameter should be guarded against unknown values,
// it's still safer to encode it to avoid cross-site scripting attacks
// if the authorization server has a relaxed policy concerning redirect URIs.
writer.WriteLine($@"<form name=""form"" method=""post"" action=""{_encoder.Encode(context.RedirectUri)}"">");
// Note: while initially not allowed by the core OAuth 2.0 specification, multiple parameters
// with the same name are used by derived drafts like the OAuth 2.0 token exchange specification.
// For consistency, multiple parameters with the same name are also supported by this endpoint.
foreach (var (key, value) in
from parameter in context.Response.GetParameters()
let values = (ImmutableArray<string?>?) parameter.Value
where values is not null
from value in values.GetValueOrDefault()
where !string.IsNullOrEmpty(value)
select (parameter.Key, Value: value))
{
writer.WriteLine($@"<input type=""hidden"" name=""{_encoder.Encode(key)}"" value=""{_encoder.Encode(value)}"" />");
}
writer.WriteLine(@"<noscript>Click here to finish the authorization process: <input type=""submit"" /></noscript>");
writer.WriteLine("</form>");
writer.WriteLine("<script>document.form.submit();</script>");
writer.WriteLine("</body>");
writer.WriteLine("</html>");
writer.Flush();
response.StatusCode = 200;
response.ContentLength = buffer.Length;
response.ContentType = "text/html;charset=UTF-8";
response.Headers[HeaderNames.CacheControl] = "no-store";
response.Headers[HeaderNames.Pragma] = "no-cache";
response.Headers[HeaderNames.Expires] = "-1";
buffer.Seek(offset: 0, loc: SeekOrigin.Begin);
await buffer.CopyToAsync(response.Body, 4096);
context.HandleRequest();
}
}
/// <summary>
/// Contains the logic responsible for processing authorization responses using the query response mode.
/// Note: this handler is not used when the OpenID Connect request is not initially handled by ASP.NET Core.
/// </summary>
public sealed class ProcessQueryResponse : IOpenIddictServerHandler<ApplyAuthorizationResponseContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ApplyAuthorizationResponseContext>()
.AddFilter<RequireHttpRequest>()
.UseSingletonHandler<ProcessQueryResponse>()
.SetOrder(ProcessFormPostResponse.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ApplyAuthorizationResponseContext context)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
if (string.IsNullOrEmpty(context.RedirectUri) ||
!string.Equals(context.ResponseMode, ResponseModes.Query, StringComparison.Ordinal))
{
return default;
}
context.Logger.LogInformation(SR.GetResourceString(SR.ID6148), context.RedirectUri, context.Response);
// Note: while initially not allowed by the core OAuth 2.0 specification, multiple parameters
// with the same name are used by derived drafts like the OAuth 2.0 token exchange specification.
// For consistency, multiple parameters with the same name are also supported by this endpoint.
#if SUPPORTS_MULTIPLE_VALUES_IN_QUERYHELPERS
var location = QueryHelpers.AddQueryString(context.RedirectUri,
from parameter in context.Response.GetParameters()
let values = (ImmutableArray<string?>?) parameter.Value
where values is not null
from value in values.GetValueOrDefault()
where !string.IsNullOrEmpty(value)
select KeyValuePair.Create(parameter.Key, value));
#else
var location = context.RedirectUri;
foreach (var (key, value) in
from parameter in context.Response.GetParameters()
let values = (ImmutableArray<string?>?) parameter.Value
where values is not null
from value in values.GetValueOrDefault()
where !string.IsNullOrEmpty(value)
select (parameter.Key, Value: value))
{
location = QueryHelpers.AddQueryString(location, key, value);
}
#endif
response.Redirect(location);
context.HandleRequest();
return default;
}
}
/// <summary>
/// Contains the logic responsible for processing authorization responses using the fragment response mode.
/// Note: this handler is not used when the OpenID Connect request is not initially handled by ASP.NET Core.
/// </summary>
public sealed class ProcessFragmentResponse : IOpenIddictServerHandler<ApplyAuthorizationResponseContext>
{
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictServerHandlerDescriptor Descriptor { get; }
= OpenIddictServerHandlerDescriptor.CreateBuilder<ApplyAuthorizationResponseContext>()
.AddFilter<RequireHttpRequest>()
.UseSingletonHandler<ProcessFragmentResponse>()
.SetOrder(ProcessQueryResponse.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
public ValueTask HandleAsync(ApplyAuthorizationResponseContext context)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
// This handler only applies to ASP.NET Core requests. If the HTTP context cannot be resolved,
// this may indicate that the request was incorrectly processed by another server stack.
var response = context.Transaction.GetHttpRequest()?.HttpContext.Response ??
throw new InvalidOperationException(SR.GetResourceString(SR.ID0114));
if (string.IsNullOrEmpty(context.RedirectUri) ||
!string.Equals(context.ResponseMode, ResponseModes.Fragment, StringComparison.Ordinal))
{
return default;
}
context.Logger.LogInformation(SR.GetResourceString(SR.ID6149), context.RedirectUri, context.Response);
var builder = new StringBuilder(context.RedirectUri);
// Note: while initially not allowed by the core OAuth 2.0 specification, multiple parameters
// with the same name are used by derived drafts like the OAuth 2.0 token exchange specification.
// For consistency, multiple parameters with the same name are also supported by this endpoint.
foreach (var (key, value) in
from parameter in context.Response.GetParameters()
let values = (ImmutableArray<string?>?) parameter.Value
where values is not null
from value in values.GetValueOrDefault()
where !string.IsNullOrEmpty(value)
select (parameter.Key, Value: value))
{
builder.Append(Contains(builder, '#') ? '&' : '#')
.Append(Uri.EscapeDataString(key))
.Append('=')
.Append(Uri.EscapeDataString(value));
}
response.Redirect(builder.ToString());
context.HandleRequest();
return default;
static bool Contains(StringBuilder builder, char delimiter)
{
for (var index = 0; index < builder.Length; index++)
{
if (builder[index] == delimiter)
{
return true;
}
}
return false;
}
}
}
}
}