Repository navigation
Expand file tree
/
Copy pathExploreAuthentication.cs
More file actions
709 lines (607 loc) · 25.2 KB
/
Copy pathExploreAuthentication.cs
File metadata and controls
709 lines (607 loc) · 25.2 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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Net.Http.Headers;
using Security.WebAppLib.IdentityCore;
using System.Security.Claims;
using System.Security.Principal;
namespace Security.WebAppLib.Example
{
public class ExploreAuthentication
{
#region Init
IServiceProvider _provider;
IAuthenticationService _authenticationService;
IAuthenticationSchemeProvider _authenticationSchemeProvider;
IOptionsMonitor<CookieAuthenticationOptions> _cookieOptions;
UserManager<IMyUser> _userManager;
SignInManager<IMyUser> _signInManager;
IHttpContextAccessor _httpContextAccessor;
public readonly string AuthCookieName =
$"{CookieAuthenticationDefaults.CookiePrefix}{IdentityConstants.ApplicationScheme}";
/// <summary>
/// Services available from DI container
/// </summary>
public ExploreAuthentication(
IServiceProvider provider,
IAuthenticationService authenticationService,
IAuthenticationSchemeProvider authenticationSchemeProvider,
IOptionsMonitor<CookieAuthenticationOptions> cookieOptions,
UserManager<IMyUser> userManager,
SignInManager<IMyUser> signInManager,
IHttpContextAccessor httpContextAccessor
)
{
_provider = provider;
this._authenticationService = authenticationService;
this._authenticationSchemeProvider = authenticationSchemeProvider;
this._cookieOptions = cookieOptions;
this._userManager = userManager;
this._signInManager = signInManager;
this._httpContextAccessor = httpContextAccessor;
}
#endregion
#region Run Tests
public async Task Run(int testNo = 0)
{
int? o = 5;
var t = o ?? testNo;
switch(t)
{
case 0:
ExploreSignInManager();
break;
case 1:
await ExploreAuthenticationSchemes();
break;
case 2:
ExploreCookieAuthenticationOptions();
break;
case 3:
await ExploreAuthenticationService();
break;
case 4:
var identity = CreateIdentity(IdentityConstants.ApplicationScheme);
await SignInWithHttpContext(identity);
break;
case 5:
await ExploreJwtScheme();
break;
}
}
#endregion
#region ExploreAuthenticationSchemes
/// <summary>
/// List all the registered authentication schemes
/// </summary>
public async Task ExploreAuthenticationSchemes()
{
// default configured authentication schemes
// when adding the Identity framework
string s = IdentityConstants.ApplicationScheme;
s = IdentityConstants.ExternalScheme;
s = IdentityConstants.TwoFactorUserIdScheme;
s = IdentityConstants.TwoFactorRememberMeScheme;
AuthenticationScheme? defaultAuthenticateScheme =
await _authenticationSchemeProvider.GetDefaultAuthenticateSchemeAsync();
if (defaultAuthenticateScheme != null)
ExploreAuthenticationScheme(defaultAuthenticateScheme);
AuthenticationScheme? defaultChallengeScheme =
await _authenticationSchemeProvider.GetDefaultChallengeSchemeAsync();
AuthenticationScheme? defaultForbidScheme =
await _authenticationSchemeProvider.GetDefaultForbidSchemeAsync();
AuthenticationScheme? defaultSignInScheme =
await _authenticationSchemeProvider.GetDefaultSignInSchemeAsync();
AuthenticationScheme? defaultSignOutScheme =
await _authenticationSchemeProvider.GetDefaultSignOutSchemeAsync();
IEnumerable<AuthenticationScheme> schemes =
await this._authenticationSchemeProvider.GetAllSchemesAsync();
foreach (var scheme in schemes)
{
string n1 = scheme.Name;
string t = scheme.HandlerType.Name;
ExploreAuthenticationScheme(scheme);
}
}
#endregion
#region ExploreAuthenticationService
public async Task ExploreAuthenticationService()
{
if (_authenticationService is AuthenticationService auth)
{
IAuthenticationSchemeProvider schemes = auth.Schemes;
await ExploreAuthenticationSchemeProvider(schemes);
IAuthenticationHandlerProvider handlers = auth.Handlers;
await ExploreAuthenticationHandlerProvider(handlers);
IClaimsTransformation transform = auth.Transform;
}
}
public async Task ExploreAuthenticationHandlerProvider(IAuthenticationHandlerProvider handlers)
{
if (GetHttpContext() is HttpContext httpContext
&& handlers is AuthenticationHandlerProvider provider)
{
await ExploreAuthenticationSchemeProvider(provider.Schemes);
// authentication logic is implemented by a specific handler
// for each authentication scheme
IAuthenticationHandler? handler = await provider.GetHandlerAsync(
httpContext, IdentityConstants.ApplicationScheme);
handler = await provider.GetHandlerAsync(
httpContext, IdentityConstants.ExternalScheme);
handler = await provider.GetHandlerAsync(
httpContext, IdentityConstants.TwoFactorUserIdScheme);
handler = await provider.GetHandlerAsync(
httpContext, IdentityConstants.TwoFactorRememberMeScheme);
handler = await provider.GetHandlerAsync(
httpContext, JwtBearerDefaults.AuthenticationScheme);
}
}
public record DefaultSchemeNames(
string? SignInScheme,
string? SignOutScheme,
string? ChallengeScheme,
string? ForbidScheme,
string? AuthenticateScheme);
/// <summary>
/// Explore the configuration of various default authentication schemes
/// for various authentication behaviors
/// </summary>
public async Task<DefaultSchemeNames?> ExploreAuthenticationSchemeProvider(
IAuthenticationSchemeProvider schemes)
{
DefaultSchemeNames? defaultSchemes = null;
if (schemes is AuthenticationSchemeProvider schemeProvider)
{
// handler responsible for sign-in logic
AuthenticationScheme? signInScheme =
await schemeProvider.GetDefaultSignInSchemeAsync();
// handler responsible for sign-out logic
AuthenticationScheme? signOutScheme =
await schemeProvider.GetDefaultSignOutSchemeAsync();
// redirect ot log-in page
AuthenticationScheme? challengeScheme =
await schemeProvider.GetDefaultChallengeSchemeAsync();
// redirect to unauthorize page
AuthenticationScheme? forbidScheme =
await schemeProvider.GetDefaultForbidSchemeAsync();
// reconstruct PrincipalClaims from cookie/token
AuthenticationScheme? authenticateScheme =
await schemeProvider.GetDefaultAuthenticateSchemeAsync();
defaultSchemes = new(signInScheme?.Name,
signOutScheme?.Name,
challengeScheme?.Name,
forbidScheme?.Name,
authenticateScheme?.Name);
IEnumerable<AuthenticationScheme> allSchemes =
await schemeProvider.GetAllSchemesAsync();
foreach (var scheme in allSchemes)
{
string n = scheme.Name;
ExploreAuthenticationScheme(scheme);
}
}
return defaultSchemes;
}
/// <summary>
/// Create and initialize a new authentication handler
/// </summary>
public async Task<IAuthenticationHandler?> GetAuthenticationHandler2(
string schemeName, HttpContext httpContext)
{
AuthenticationScheme? scheme =
await _authenticationSchemeProvider.GetSchemeAsync(schemeName);
if (scheme != null
&& _provider.GetService(scheme.HandlerType) is IAuthenticationHandler authHandler)
{
// new handler will need to be intialized
await authHandler.InitializeAsync(scheme, httpContext);
return authHandler;
}
return null;
}
/// <summary>
/// Create and initialize a new authentication handler
/// </summary>
public async Task<IAuthenticationHandler?> GetAuthenticationHandler(
string schemeName, HttpContext httpContext)
{
if (_authenticationService is AuthenticationService auth)
{
IAuthenticationHandler? handler =
await auth.Handlers.GetHandlerAsync(httpContext, schemeName);
return handler;
}
return null;
}
#endregion
#region CookieAuthenticationOptions
/// <summary>
/// Configuration for authentication cookie
/// </summary>
public void ExploreCookieAuthenticationOptions()
{
PathString ps = CookieAuthenticationDefaults.LogoutPath;
ps = CookieAuthenticationDefaults.LoginPath;
string s = CookieAuthenticationDefaults.ReturnUrlParameter;
s = CookieAuthenticationDefaults.CookiePrefix;
s = CookieAuthenticationDefaults.AuthenticationScheme;
CookieAuthenticationOptions options = _cookieOptions.Get(IdentityConstants.ApplicationScheme);
if (options != null)
ExploreCookieOptions(options);
options = _cookieOptions.Get(IdentityConstants.ExternalScheme);
if (options != null)
ExploreCookieOptions(options);
options = _cookieOptions.Get(IdentityConstants.TwoFactorUserIdScheme);
if (options != null)
ExploreCookieOptions(options);
options = _cookieOptions.Get(IdentityConstants.TwoFactorRememberMeScheme);
if (options != null)
ExploreCookieOptions(options);
}
public void ExploreCookieOptions(CookieAuthenticationOptions options)
{
AuthenticationSchemeOptions o1 = options;
string? s = o1.ClaimsIssuer;
s = o1.ForwardAuthenticate;
s = o1.ForwardChallenge;
s = o1.ForwardDefault;
s = o1.ForwardForbid;
s = o1.ForwardSignIn;
s = o1.ForwardSignOut;
object? e = o1.Events;
s = o1.EventsType?.Name;
s = options.AccessDeniedPath;
s = options.ReturnUrlParameter;
CookieBuilder b = options.Cookie;
ICookieManager cm = options.CookieManager;
IDataProtectionProvider? dp = options.DataProtectionProvider;
CookieAuthenticationEvents ev = options.Events;
TimeSpan ex = options.ExpireTimeSpan;
PathString ps = options.LoginPath;
ps = options.LogoutPath;
ITicketStore? ts = options.SessionStore;
bool b2 = options.SlidingExpiration;
ISecureDataFormat<AuthenticationTicket> f = options.TicketDataFormat;
}
#endregion
#region Explore SignInManager
/// <summary>
/// Sign-In logic
/// </summary>
public void ExploreSignInManager()
{
if (GetHttpContext(_signInManager) is HttpContext context)
{
ExploreHttpContext(context);
var b = _signInManager.IsSignedIn(context.User);
var identity = CreateIdentity(IdentityConstants.ApplicationScheme);
context.User = new ClaimsPrincipal(identity);
ExploreHttpContext(context);
// signInManager only recognizes identity with
// authentication type of IdentityConstants.ApplicationScheme
b = _signInManager.IsSignedIn(context.User);
}
IdentityOptions options = _signInManager.Options;
UserManager<IMyUser> userManager = _signInManager.UserManager;
IUserClaimsPrincipalFactory<IMyUser> claimFact = _signInManager.ClaimsFactory;
}
#endregion
#region Test SignIn
public DefaultSchemeNames? DefaultSchemes
{
get
{
if (field == null)
field = ExploreAuthenticationSchemeProvider(_authenticationSchemeProvider).Result;
return field;
}
protected set;
}
/// <summary>
/// Various sign-In logic
/// </summary>
public async Task SignInWithManager(IMyUser user)
{
try { await _signInManager.SignInAsync(user, true); }
catch (Exception ex)
{
string s = ex.Message;
}
if (GetHttpContext(_signInManager) is HttpContext httpContext)
ExploreHttpContext(httpContext);
}
/// <summary>
/// Various sign-In logic
/// </summary>
public async Task SignInWithHttpContext(ClaimsIdentity identity)
{
var u = new ClaimsPrincipal(identity);
if (GetHttpContext(_signInManager) is HttpContext httpContext)
{
try
{
string signInScheme = DefaultSchemes?.SignInScheme ?? IdentityConstants.ApplicationScheme;
await httpContext.SignInAsync(signInScheme, u);
ValidateSignIn(signInScheme, httpContext.Response);
}
catch (Exception ex)
{
string s = ex.Message;
}
}
}
/// <summary>
/// Various sign-In logic
/// </summary>
public async Task SignInWithAuthenticationService(ClaimsIdentity identity)
{
var u = new ClaimsPrincipal(identity);
if (GetHttpContext(_signInManager) is HttpContext httpContext
&& _authenticationService is AuthenticationService authService)
{
try {
await authService.SignInAsync(
httpContext,
IdentityConstants.ApplicationScheme,
u,
new());
}
catch (Exception ex)
{
string s = ex.Message;
}
}
}
/// <summary>
/// Various sign-In logic
/// </summary>
public async Task SignInWithCookieHandler(ClaimsIdentity identity)
{
var u = new ClaimsPrincipal(identity);
if (_authenticationService is AuthenticationService authService)
{
AuthenticationScheme? signInScheme =
await authService.Schemes.GetDefaultSignInSchemeAsync();
object? o = null;
if (signInScheme != null && signInScheme.HandlerType != null)
{
o = _provider.GetService(signInScheme.HandlerType);
string n = signInScheme.Name;
}
if (o is CookieAuthenticationHandler cookieHandler)
{
try
{
await cookieHandler.SignInAsync(u, new());
}
catch (Exception ex)
{
string message = ex.Message;
}
}
}
}
public async Task SignOut()
{
await _signInManager.SignOutAsync();
}
public void ValidateSignIn(string signInScheme, HttpResponse response)
{
SetCookieHeaderValue? authCookie = ExploreAuthCookies(response);
if (authCookie != null)
{
AuthenticationTicket? ticket =
ParseAuthCookie(signInScheme, authCookie.Value.ToString());
if (ticket != null)
ExploreAuthenticationTicket(ticket);
}
}
public AuthenticationTicket? ParseAuthCookie(string scheme, string cookieValue)
{
CookieAuthenticationOptions options = _cookieOptions.Get(scheme);
AuthenticationTicket? ticket = options.TicketDataFormat.Unprotect(cookieValue);
return ticket;
}
#endregion
#region JWT
public async Task ExploreJwtScheme()
{
if (GetHttpContext() is HttpContext httpContext)
{
IAuthenticationHandler? handler =
await GetAuthenticationHandler(JwtBearerDefaults.AuthenticationScheme, httpContext);
if (handler is JwtBearerHandler jwtHandler)
{
JwtBearerOptions options =
_provider.GetRequiredService<IOptionsMonitor<JwtBearerOptions>>().CurrentValue;
TokenValidationParameters validation = options.TokenValidationParameters;
JwtConfig cfg = _provider.GetRequiredService<IOptions<JwtConfig>>().Value;
ClaimsIdentity identity = CreateIdentity(cfg.AuthenticationType);
string jwt = CreateJwtToken(cfg, identity);
await ExploreJwtToken(cfg, jwt);
httpContext.Request.Headers[HeaderNames.Authorization] = $"Bearer {jwt}";
AuthenticateResult res = await jwtHandler.AuthenticateAsync();
if (res.Succeeded)
{
AuthenticationTicket t = res.Ticket;
ExploreAuthenticationTicket(t);
ClaimsPrincipal p = t.Principal;
httpContext.User = p;
}
else if (res.Failure is Exception e)
{
var msg = e.Message;
}
}
}
}
public string CreateJwtToken(JwtConfig cfg, ClaimsIdentity identity)
{
SecurityTokenDescriptor d = JwtUtil.GetSecurityTokenDescriptor(cfg, identity);
string jwt = JwtUtil.CreateToken(d);
return jwt;
}
public async Task ExploreJwtToken(JwtConfig cfg, string token)
{
TokenValidationParameters v = JwtUtil.GetValidatOption(cfg);
if (await JwtUtil.ValidateTokenAsync(token, v) is TokenValidationResult res)
{
}
if (JwtUtil.TryGetToken(token, out JsonWebToken jwtToken))
{
}
}
#endregion
#region Explore
public void ExploreHttpContext(HttpContext httpContext)
{
ClaimsPrincipal user = httpContext.User;
IEnumerable<Claim> claims = user.Claims;
var cnt = claims.Count();
IEnumerable<IIdentity> identities = httpContext.User.Identities;
cnt = user.Identities.Count();
if (user.Identity is IIdentity identity)
{
bool b = identity.IsAuthenticated;
string? name = identity.Name;
string? scheme = identity.AuthenticationType;
}
}
public void ExploreAuthenticationScheme(AuthenticationScheme scheme)
{
string? n = scheme.DisplayName;
string n1 = scheme.Name;
string t = scheme.HandlerType.Name;
object? o = _provider.GetService(scheme.HandlerType);
bool b = o is IAuthenticationSignInHandler;
b = o is IAuthenticationSignOutHandler;
if (o is IAuthenticationHandler handler)
{
ExploreAuthenticationHandler(handler);
}
}
public void ExploreAuthenticationHandler(IAuthenticationHandler handler)
{
bool b = handler is IAuthenticationSignInHandler;
b = handler is IAuthenticationSignOutHandler;
if (handler is CookieAuthenticationHandler cookieHandler)
{
ExploreCookieAuthenticationHandler(cookieHandler);
};
}
public void ExploreCookieAuthenticationHandler(CookieAuthenticationHandler handler)
{
AuthenticationScheme s = handler.Scheme;
if (handler.Options is CookieAuthenticationOptions op)
ExploreCookieOptions(op);
if (handler is AuthenticationHandler<CookieAuthenticationOptions> authHandler)
{
bool b = authHandler is IAuthenticationSignInHandler;
b = authHandler is IAuthenticationSignOutHandler;
}
if (handler is SignInAuthenticationHandler<CookieAuthenticationOptions> signInHandler)
{
}
if (handler is SignOutAuthenticationHandler<CookieAuthenticationOptions> sigOutHandler)
{
}
}
public SetCookieHeaderValue? ExploreAuthCookies(HttpResponse response)
{
SetCookieHeaderValue? authCookie = null;
if (response.Headers.TryGetValue(HeaderNames.SetCookie, out StringValues vals))
{
foreach (string? val in vals)
{
if (SetCookieHeaderValue.TryParse(val, out SetCookieHeaderValue? cookieVal))
{
StringSegment s = cookieVal.Domain;
DateTimeOffset? d = cookieVal.Expires;
IList<StringSegment> e = cookieVal.Extensions;
bool b = cookieVal.HttpOnly;
TimeSpan? t = cookieVal.MaxAge;
s = cookieVal.Name;
s = cookieVal.Path;
var m = cookieVal.SameSite;
b = cookieVal.Secure;
s = cookieVal.Value;
if (cookieVal.Name == AuthCookieName)
{
authCookie = cookieVal;
}
}
}
}
return authCookie;
}
public string? ExploreAuthCookies(HttpRequest request)
{
string? authCookie = null;
foreach (KeyValuePair<string, string> cookie in request.Cookies)
{
string name = cookie.Key;
string value = cookie.Value;
if (name == AuthCookieName)
{
authCookie = $"{name}={value}";
}
}
return authCookie;
}
public void ExploreAuthenticationTicket(AuthenticationTicket ticket)
{
ClaimsPrincipal principal = ticket.Principal;
AuthenticationProperties properties = ticket.Properties;
DateTimeOffset? issuedUtc = properties.IssuedUtc;
DateTimeOffset? expiresUtc = properties.ExpiresUtc;
bool? allowRefresh = properties.AllowRefresh;
string? redirectUri = properties.RedirectUri;
IDictionary<string, string?> items = properties.Items;
IList<string> list = properties.Parameters.Keys.ToList();
}
#endregion
#region Test data
public HttpContext? GetHttpContext(object? o = null)
{
HttpContext? c = null;
try
{
c = o switch
{
SignInManager<IMyUser> s => s.Context,
_ => _httpContextAccessor.HttpContext
};
}
catch { }
return c;
}
public IMyUser CreateUser()
{
var user = new MyUser()
{
Name = "Joe Smith",
UserName = "U123A",
ID = "123",
Email = "joe.smith@example.com",
SecurityStamp = "123"
};
return user;
}
public ClaimsIdentity CreateIdentity(string? authenticationType = null)
{
var claims = new List<Claim>
{
new(ClaimTypes.Name, "Joe Smith"),
};
var identity = new ClaimsIdentity(claims, authenticationType);
return identity;
}
#endregion
}
}