-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
AccountController.cs
1198 lines (1042 loc) · 48.6 KB
/
AccountController.cs
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
// Original file: https://github.com/IdentityServer/IdentityServer4.Samples
// Modified by Jan Škoruba
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Security.Principal;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using IdentityModel;
using IdentityServer4;
using IdentityServer4.Events;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using Skoruba.IdentityServer4.Shared.Configuration.Identity;
using Skoruba.IdentityServer4.STS.Identity.Configuration;
using Skoruba.IdentityServer4.STS.Identity.Configuration.Constants;
using Skoruba.IdentityServer4.STS.Identity.Helpers;
using Skoruba.IdentityServer4.STS.Identity.Helpers.ADUtilities;
using Skoruba.IdentityServer4.STS.Identity.Helpers.Localization;
using Skoruba.IdentityServer4.STS.Identity.ViewModels.Account;
namespace Skoruba.IdentityServer4.STS.Identity.Controllers
{
[SecurityHeaders]
[Authorize]
public class AccountController<TUser, TKey> : Controller
where TUser : IdentityUser<TKey>, new()
where TKey : IEquatable<TKey>
{
private readonly UserResolver<TUser> _userResolver;
private readonly UserManager<TUser> _userManager;
private readonly SignInManager<TUser> _signInManager;
private readonly IIdentityServerInteractionService _interaction;
private readonly IClientStore _clientStore;
private readonly IAuthenticationSchemeProvider _schemeProvider;
private readonly IEventService _events;
private readonly IEmailSender _emailSender;
private readonly IGenericControllerLocalizer<AccountController<TUser, TKey>> _localizer;
private readonly LoginConfiguration _loginConfiguration;
private readonly RegisterConfiguration _registerConfiguration;
private readonly IdentityOptions _identityOptions;
private readonly ILogger<AccountController<TUser, TKey>> _logger;
private readonly WindowsAuthConfiguration _windowsAuthConfiguration;
private readonly IADUtilities _ADUtilities;
public AccountController(
UserResolver<TUser> userResolver,
UserManager<TUser> userManager,
SignInManager<TUser> signInManager,
IIdentityServerInteractionService interaction,
IClientStore clientStore,
IAuthenticationSchemeProvider schemeProvider,
IEventService events,
IEmailSender emailSender,
IGenericControllerLocalizer<AccountController<TUser, TKey>> localizer,
LoginConfiguration loginConfiguration,
WindowsAuthConfiguration windowsAuthConfiguration,
IADUtilities adUtilities,
RegisterConfiguration registerConfiguration,
IdentityOptions identityOptions,
ILogger<AccountController<TUser, TKey>> logger)
{
_userResolver = userResolver;
_userManager = userManager;
_signInManager = signInManager;
_interaction = interaction;
_clientStore = clientStore;
_schemeProvider = schemeProvider;
_events = events;
_emailSender = emailSender;
_localizer = localizer;
_loginConfiguration = loginConfiguration;
_windowsAuthConfiguration = windowsAuthConfiguration;
_ADUtilities = adUtilities;
_registerConfiguration = registerConfiguration;
_identityOptions = identityOptions;
_logger = logger;
}
/// <summary>
/// Entry point into the login workflow
/// </summary>
/// <param name="returnUrl"></param>
/// <param name="forceLoginScreen">When true, ignores the AutomaticWindowsLogin setting</param>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> Login(string returnUrl, bool forceLoginScreen = false)
{
if (_windowsAuthConfiguration.AutomaticWindowsLogin && !forceLoginScreen && Request.IsFromLocalSubnet(_windowsAuthConfiguration.ExcludedLocalSubnets, _logger))
{
return RedirectToAction("ExternalLogin", new { provider = AccountOptions.WindowsAuthenticationSchemeName, returnUrl });
}
// build a model so we know what to show on the login page
var vm = await BuildLoginViewModelAsync(returnUrl);
if (vm.IsExternalLoginOnly)
{
// we only have one option for logging in and it's an external provider
return RedirectToAction("ExternalLogin", new { provider = vm.ExternalLoginScheme, returnUrl });
}
return View(vm);
}
/// <summary>
/// Handle postback from username/password login
/// </summary>
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginInputModel model, string button)
{
// check if we are in the context of an authorization request
var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);
// the user clicked the "cancel" button
if (button != "login")
{
if (context != null)
{
// if the user cancels, send a result back into IdentityServer as if they
// denied the consent (even if this client does not require consent).
// this will send back an access denied OIDC error response to the client.
await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);
// we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
if (await _clientStore.IsPkceClientAsync(context.ClientId))
{
// if the client is PKCE then we assume it's native, so this change in how to
// return the response is for better UX for the end user.
return View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl });
}
return Redirect(model.ReturnUrl);
}
// since we don't have a valid context, then we just go back to the home page
return Redirect("~/");
}
if (ModelState.IsValid)
{
var user = await _userResolver.GetUserAsync(model.Username);
if (user != default(TUser))
{
var result = await _signInManager.PasswordSignInAsync(user.UserName, model.Password, model.RememberLogin, lockoutOnFailure: true);
if (result.Succeeded)
{
await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id.ToString(), user.UserName));
if (context != null)
{
if (await _clientStore.IsPkceClientAsync(context.ClientId))
{
// if the client is PKCE then we assume it's native, so this change in how to
// return the response is for better UX for the end user.
return View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl });
}
// we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
return Redirect(model.ReturnUrl);
}
// request for a local page
if (Url.IsLocalUrl(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
if (string.IsNullOrEmpty(model.ReturnUrl))
{
return Redirect("~/");
}
// user might have clicked on a malicious link - should be logged
throw new Exception("invalid return URL");
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(LoginWith2fa), new { model.ReturnUrl, RememberMe = model.RememberLogin });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
}
await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));
ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
}
// something went wrong, show form with error
var vm = await BuildLoginViewModelAsync(model);
return View(vm);
}
[HttpGet]
[AllowAnonymous]
public IActionResult WindowsLogin(string returnUrl)
{
LoginInputModel vm = new LoginInputModel { ReturnUrl = returnUrl };
return View(vm);
}
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> WindowsLogin(LoginInputModel vm)
{
if (ModelState.IsValid)
{
// Username can be in the format domain\username or just the Windows username.
// In the latter case, the host domain will be used.
var usernameParts = vm.Username.Split('\\', StringSplitOptions.RemoveEmptyEntries);
if (usernameParts.Length > 2)
ModelState.AddModelError("Username", _localizer["InvalidUsernameFormat"]);
else
{
var wi = _ADUtilities.LogonWindowsUser(usernameParts.Length > 1 ? usernameParts[1] : usernameParts[0],
vm.Password,
usernameParts.Length > 1 ? usernameParts[0] : null);
if (wi != null)
return await IssueExternalCookie(vm.ReturnUrl, wi);
ModelState.AddModelError(string.Empty, _localizer["WindowsAuthenticationFailed"]);
}
}
return View(vm);
}
private async Task<IActionResult> IssueExternalCookie(string returnUrl, IIdentity wi)
{
var adProperties = _ADUtilities.GetUserInfoFromAD(wi.Name);
var id = new ClaimsIdentity(AccountOptions.WindowsAuthenticationSchemeName);
var name = wi.Name;
name = name.Substring(name.IndexOf('\\') + 1);
id.AddClaim(new Claim(JwtClaimTypes.Subject, name));
id.AddClaim(new Claim(ClaimTypes.NameIdentifier, name));
id.AddClaim(new Claim(JwtClaimTypes.Name, adProperties.DisplayName));
id.AddClaim(new Claim(JwtClaimTypes.Email, adProperties.Email));
// we will issue the external cookie and then redirect the
// user back to the external callback, in essence, treating windows
// auth the same as any other external authentication mechanism
var props = new AuthenticationProperties()
{
RedirectUri = Url.Action("ExternalLoginCallback"),
Items =
{
{ "returnUrl", returnUrl },
{ "LoginProvider", AccountOptions.WindowsAuthenticationSchemeName },
}
};
await HttpContext.SignInAsync(
IdentityConstants.ExternalScheme,
new ClaimsPrincipal(id),
props);
return Redirect(props.RedirectUri);
}
/// <summary>
/// Show logout page
/// </summary>
[HttpGet]
public async Task<IActionResult> Logout(string logoutId)
{
// build a model so the logout page knows what to display
var vm = await BuildLogoutViewModelAsync(logoutId);
if (vm.ShowLogoutPrompt == false)
{
// if the request for logout was properly authenticated from IdentityServer, then
// we don't need to show the prompt and can just log the user out directly.
return await Logout(vm);
}
return View(vm);
}
/// <summary>
/// Handle logout page postback
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Logout(LogoutInputModel model)
{
// build a model so the logged out page knows what to display
var vm = await BuildLoggedOutViewModelAsync(model.LogoutId);
if (User?.Identity.IsAuthenticated == true)
{
// delete local authentication cookie
await _signInManager.SignOutAsync();
// raise the logout event
await _events.RaiseAsync(new UserLogoutSuccessEvent(User.GetSubjectId(), User.GetDisplayName()));
}
// check if we need to trigger sign-out at an upstream identity provider
if (vm.TriggerExternalSignout)
{
// build a return URL so the upstream provider will redirect back
// to us after the user has logged out. this allows us to then
// complete our single sign-out processing.
string url = Url.Action("Logout", new { logoutId = vm.LogoutId });
// this triggers a redirect to the external provider for sign-out
return SignOut(new AuthenticationProperties { RedirectUri = url }, vm.ExternalAuthenticationScheme);
}
return View("LoggedOut", vm);
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View(new ForgotPasswordViewModel());
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
TUser user = null;
switch (model.Policy)
{
case LoginResolutionPolicy.Email:
try
{
user = await _userManager.FindByEmailAsync(model.Email);
}
catch (Exception ex)
{
// in case of multiple users with the same email this method would throw and reveal that the email is registered
_logger.LogError("Error retrieving user by email ({0}) for forgot password functionality: {1}", model.Email, ex.Message);
user = null;
}
break;
case LoginResolutionPolicy.Username:
user = await _userManager.FindByNameAsync(model.Username);
break;
}
if (user == null || !await _userManager.IsEmailConfirmedAsync(user))
{
// Don't reveal that the user does not exist
return View("ForgotPasswordConfirmation");
}
var code = await _userManager.GeneratePasswordResetTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code }, HttpContext.Request.Scheme);
await _emailSender.SendEmailAsync(user.Email, _localizer["ResetPasswordTitle"], _localizer["ResetPasswordBody", HtmlEncoder.Default.Encode(callbackUrl)]);
return View("ForgotPasswordConfirmation");
}
return View(model);
}
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
return code == null ? View("Error") : View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByEmailAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction(nameof(ResetPasswordConfirmation), "Account");
}
var code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(model.Code));
var result = await _userManager.ResetPasswordAsync(user, code, model.Password);
if (result.Succeeded)
{
return RedirectToAction(nameof(ResetPasswordConfirmation), "Account");
}
AddErrors(result);
return View();
}
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPasswordConfirmation()
{
return View();
}
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPasswordConfirmation()
{
return View();
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
ModelState.AddModelError(string.Empty, _localizer["ErrorExternalProvider", remoteError]);
var vm = await BuildLoginViewModelAsync(returnUrl);
return View(nameof(Login), vm);
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction(nameof(Login), new { returnUrl });
}
var externalResult = await HttpContext.AuthenticateAsync(IdentityConstants.ExternalScheme);
if (externalResult.Succeeded)
{
if (externalResult.Properties.Items.ContainsKey("returnUrl"))
returnUrl = externalResult.Properties.Items["returnUrl"];
// We no longer need the external cookie
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
if (info.LoginProvider == AccountOptions.WindowsAuthenticationSchemeName &&
_windowsAuthConfiguration.SyncUserProfileWithWindows)
{
await SyncUserProfileWithAD(info);
}
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(LoginWith2fa), new { ReturnUrl = returnUrl });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
// If we already collected username and email of the user, auto-provision the user
var username = info.Principal.FindFirstValue(ClaimTypes.NameIdentifier) ?? info.Principal.FindFirstValue(JwtClaimTypes.Subject);
var email = info.Principal.FindFirstValue(ClaimTypes.Email) ?? info.Principal.FindFirstValue(JwtClaimTypes.Email);
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(email))
{
var user = await ProvideExternalUserAsync(info, username, email);
if (user == null)
{
var vm = await BuildLoginViewModelAsync(returnUrl);
return View(nameof(Login), vm);
}
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToLocal(returnUrl);
}
// Otherwise ask the user to fill the missing data to create an account
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email, UserName = username });
}
private async Task SyncUserProfileWithAD(ExternalLoginInfo info)
{
var adInfo = _ADUtilities.GetUserInfoFromAD(info.ProviderKey);
var user = await _userResolver.GetUserAsync(info.ProviderKey);
user.Email = adInfo.Email;
user.NormalizedEmail = adInfo.Email?.ToUpper();
user.EmailConfirmed = !string.IsNullOrEmpty(adInfo.Email);
user.PhoneNumber = adInfo.PhoneNumber;
var currentClaims = await _userManager.GetClaimsAsync(user);
await UpdateUserClaim(user, currentClaims, JwtClaimTypes.Email, adInfo.Email);
await UpdateUserClaim(user, currentClaims, JwtClaimTypes.Picture, adInfo.Photo);
await UpdateUserClaim(user, currentClaims, JwtClaimTypes.WebSite, adInfo.WebSite);
await UpdateUserClaim(user, currentClaims, JwtClaimTypes.Address,
(!string.IsNullOrEmpty(adInfo.Country) || !string.IsNullOrEmpty(adInfo.StreetAddress)) ?
Newtonsoft.Json.JsonConvert.SerializeObject(new { country = adInfo.Country, street_address = adInfo.StreetAddress }) :
null);
if (_windowsAuthConfiguration.IncludeWindowsGroups)
{
// Remove the groups that the user doesn't belong to anymore.
// If a policy has been configured for choosing which AD groups should become user claims
// (via WindowsGroupsPrefix and WindowsGroupsOURoot settings), only those complying with that policy will be removed
foreach (var currentGroup in _ADUtilities.FilterADGroups(currentClaims.Where(c => c.Type == JwtClaimTypes.Role).Select(c => c.Value)))
{
if (!adInfo.Groups.Contains(currentGroup))
{
var removeClaimRes = await _userManager.RemoveClaimAsync(user, currentClaims.First(c => c.Type == JwtClaimTypes.Role && c.Value == currentGroup));
if (!removeClaimRes.Succeeded)
{
_logger.LogError(_localizer["ErrorRemovingRoleClaim", currentGroup, user.UserName]);
foreach (var error in removeClaimRes.Errors)
{
_logger.LogError(error.Description);
}
}
}
}
// Add new groups
foreach (var newGroup in adInfo.Groups)
{
if (currentClaims.FirstOrDefault(c => c.Type == JwtClaimTypes.Role && c.Value == newGroup) == null)
{
var addClaimRes = await _userManager.AddClaimAsync(user, new Claim(JwtClaimTypes.Role, newGroup));
if (!addClaimRes.Succeeded)
{
_logger.LogError(_localizer["ErrorAddingRoleClaim", newGroup, user.UserName]);
foreach (var error in addClaimRes.Errors)
{
_logger.LogError(error.Description);
}
}
}
}
}
var updateUserRes = await _userManager.UpdateAsync(user);
if (!updateUserRes.Succeeded)
{
_logger.LogError(_localizer["ErrorSyncingUserProfile", user.UserName]);
foreach (var error in updateUserRes.Errors)
{
_logger.LogError(error.Description);
}
}
}
private async Task<IdentityResult> UpdateUserClaim(TUser user, IList<Claim> currentClaims, string claimType, string claimNewValue)
{
IdentityResult res = IdentityResult.Success;
var currentClaim = currentClaims.FirstOrDefault(c => c.Type == claimType);
if (currentClaim != null)
{
if (string.IsNullOrEmpty(claimNewValue))
res = await _userManager.RemoveClaimAsync(user, currentClaim);
else if (currentClaim.Value != claimNewValue)
res = await _userManager.ReplaceClaimAsync(user, currentClaim, new Claim(claimType, claimNewValue));
}
else if (!string.IsNullOrEmpty(claimNewValue))
res = await _userManager.AddClaimAsync(user, new Claim(claimType, claimNewValue));
if (!res.Succeeded)
{
_logger.LogError(_localizer["ErrorUpdatingClaim", claimType, user.UserName, claimNewValue]);
foreach (var error in res.Errors)
{
_logger.LogError(error.Description);
}
}
return res;
}
[HttpPost]
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLogin(string provider, string returnUrl = null)
{
if (string.IsNullOrEmpty(returnUrl))
returnUrl = "~/";
// validate returnUrl - either it is a valid OIDC URL or back to a local page
if (Url.IsLocalUrl(returnUrl) == false && _interaction.IsValidReturnUrl(returnUrl) == false)
{
// user might have clicked on a malicious link - should be logged
throw new Exception("invalid return URL");
}
if (AccountOptions.WindowsAuthenticationSchemeName == provider)
{
// windows authentication needs special handling
return await ProcessWindowsLoginAsync(returnUrl);
}
else
{
// start challenge and roundtrip the return URL and scheme
// Request a redirect to the external login provider.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return Challenge(properties, provider);
}
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
if (ModelState.IsValid)
{
var user = await ProvideExternalUserAsync(info, model.UserName, model.Email);
if (user != null)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToLocal(returnUrl);
}
}
ViewData["LoginProvider"] = info.LoginProvider;
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> LoginWithRecoveryCode(string returnUrl = null)
{
// Ensure the user has gone through the username & password screen first
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new InvalidOperationException(_localizer["Unable2FA"]);
}
var model = new LoginWithRecoveryCodeViewModel()
{
ReturnUrl = returnUrl
};
return View(model);
}
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> LoginWithRecoveryCode(LoginWithRecoveryCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new InvalidOperationException(_localizer["Unable2FA"]);
}
var recoveryCode = model.RecoveryCode.Replace(" ", string.Empty);
var result = await _signInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode);
if (result.Succeeded)
{
return LocalRedirect(string.IsNullOrEmpty(model.ReturnUrl) ? "~/" : model.ReturnUrl);
}
if (result.IsLockedOut)
{
return View("Lockout");
}
ModelState.AddModelError(string.Empty, _localizer["InvalidRecoveryCode"]);
return View(model);
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> LoginWith2fa(bool rememberMe, string returnUrl = null)
{
// Ensure the user has gone through the username & password screen first
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new InvalidOperationException(_localizer["Unable2FA"]);
}
var model = new LoginWith2faViewModel()
{
ReturnUrl = returnUrl,
RememberMe = rememberMe
};
return View(model);
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LoginWith2fa(LoginWith2faViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
throw new InvalidOperationException(_localizer["Unable2FA"]);
}
var authenticatorCode = model.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty);
var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, model.RememberMe, model.RememberMachine);
if (result.Succeeded)
{
return LocalRedirect(string.IsNullOrEmpty(model.ReturnUrl) ? "~/" : model.ReturnUrl);
}
if (result.IsLockedOut)
{
return View("Lockout");
}
ModelState.AddModelError(string.Empty, _localizer["InvalidAuthenticatorCode"]);
return View(model);
}
[HttpGet]
[AllowAnonymous]
public IActionResult Register(string returnUrl = null)
{
if (!_registerConfiguration.Enabled) return View("RegisterFailure");
ViewData["ReturnUrl"] = returnUrl;
switch (_loginConfiguration.ResolutionPolicy)
{
case LoginResolutionPolicy.Username:
return View();
case LoginResolutionPolicy.Email:
return View("RegisterWithoutUsername");
default:
return View("RegisterFailure");
}
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null, bool IsCalledFromRegisterWithoutUsername = false)
{
returnUrl = returnUrl ?? Url.Content("~/");
ViewData["ReturnUrl"] = returnUrl;
if (!ModelState.IsValid) return View(model);
var user = new TUser
{
UserName = model.UserName,
Email = model.Email
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code }, HttpContext.Request.Scheme);
await _emailSender.SendEmailAsync(model.Email, _localizer["ConfirmEmailTitle"], _localizer["ConfirmEmailBody", HtmlEncoder.Default.Encode(callbackUrl)]);
if (_identityOptions.SignIn.RequireConfirmedAccount)
{
return View("RegisterConfirmation");
}
else
{
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
}
AddErrors(result);
// If we got this far, something failed, redisplay form
if (IsCalledFromRegisterWithoutUsername)
{
var registerWithoutUsernameModel = new RegisterWithoutUsernameViewModel
{
Email = model.Email,
Password = model.Password,
ConfirmPassword = model.ConfirmPassword
};
return View("RegisterWithoutUsername", registerWithoutUsernameModel);
}
else
{
return View(model);
}
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RegisterWithoutUsername(RegisterWithoutUsernameViewModel model, string returnUrl = null)
{
var registerModel = new RegisterViewModel
{
UserName = model.Email,
Email = model.Email,
Password = model.Password,
ConfirmPassword = model.ConfirmPassword
};
return await Register(registerModel, returnUrl, true);
}
[HttpGet]
public IActionResult ImportAllWindowsUsers()
{
return View(new ImportAllWindowsUsersViewModel());
}
[HttpPost]
[Authorize(AuthorizationConsts.AdministrationPolicy)]
public async Task<IActionResult> ImportAllWindowsUsers(ImportAllWindowsUsersViewModel model)
{
int nErrors = 0, nImported = 0, nUpdated = 0;
foreach (var username in _ADUtilities.ReadAllUsernamesFromAD())
{
try
{
var loginInfo = new ExternalLoginInfo(new ClaimsPrincipal(new ClaimsIdentity()), AccountOptions.WindowsAuthenticationSchemeName, username, null);
var existingUser = await _userManager.FindByLoginAsync(AccountOptions.WindowsAuthenticationSchemeName, username);
if (existingUser == null)
{
await ProvideExternalUserAsync(loginInfo, username, null);
nImported++;
}
else if (_windowsAuthConfiguration.SyncUserProfileWithWindows)
{
await SyncUserProfileWithAD(loginInfo);
nUpdated++;
}
}
catch (Exception ex)
{
nErrors++;
_logger.LogError(ex, "Error importing user {0}", username);
}
}
model.StatusMessage = _localizer["WindowsUsersImported", nImported, nUpdated, nErrors];
return View(model);
}
/*****************************************/
/* helper APIs for the AccountController */
/*****************************************/
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction(nameof(HomeController.Index), "Home");
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private async Task<LoginViewModel> BuildLoginViewModelAsync(string returnUrl)
{
var context = await _interaction.GetAuthorizationContextAsync(returnUrl);
if (context?.IdP != null)
{
// this is meant to short circuit the UI and only trigger the one external IdP
return new LoginViewModel
{
EnableLocalLogin = false,
ReturnUrl = returnUrl,
Username = context?.LoginHint,
LoginResolutionPolicy = _loginConfiguration.ResolutionPolicy,
ExternalProviders = new ExternalProvider[] { new ExternalProvider { AuthenticationScheme = context.IdP } }
};
}
var schemes = await _schemeProvider.GetAllSchemesAsync();
var providers = schemes
.Where(x => x.DisplayName != null ||
(x.Name.Equals(AccountOptions.WindowsAuthenticationSchemeName, StringComparison.OrdinalIgnoreCase))
)
.Select(x => new ExternalProvider
{
DisplayName = x.DisplayName ?? x.Name, // https://github.com/IdentityServer/IdentityServer4/issues/1607
AuthenticationScheme = x.Name
}).ToList();
var allowLocal = true;
if (context?.ClientId != null)
{
var client = await _clientStore.FindEnabledClientByIdAsync(context.ClientId);
if (client != null)
{
allowLocal = client.EnableLocalLogin;
if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
{
providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList();
}
}
}
return new LoginViewModel
{
AllowRememberLogin = AccountOptions.AllowRememberLogin,
EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin,
ReturnUrl = returnUrl,
Username = context?.LoginHint,
LoginResolutionPolicy = _loginConfiguration.ResolutionPolicy,
ExternalProviders = providers.ToArray()
};
}
private async Task<LoginViewModel> BuildLoginViewModelAsync(LoginInputModel model)
{