/
AuthenticationService.cs
897 lines (748 loc) · 35.7 KB
/
AuthenticationService.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
// 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.Collections.Generic;
using System.Data.Entity;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web.Mvc;
using Microsoft.Owin;
using NuGetGallery.Auditing;
using NuGetGallery.Authentication.Providers;
using NuGetGallery.Authentication.Providers.AzureActiveDirectoryV2;
using NuGetGallery.Configuration;
using NuGetGallery.Diagnostics;
using NuGetGallery.Infrastructure.Authentication;
using static NuGetGallery.Constants;
namespace NuGetGallery.Authentication
{
public class AuthenticationService
{
private Dictionary<string, Func<string, string>> _credentialFormatters;
private readonly IDiagnosticsSource _trace;
private readonly IAppConfiguration _config;
private readonly ICredentialBuilder _credentialBuilder;
private readonly ICredentialValidator _credentialValidator;
private readonly IDateTimeProvider _dateTimeProvider;
private readonly IContentObjectService _contentObjectService;
private readonly ITelemetryService _telemetryService;
/// <summary>
/// This ctor is used for test only.
/// </summary>
protected AuthenticationService()
{
Auditing = AuditingService.None;
Authenticators = new Dictionary<string, Authenticator>();
InitCredentialFormatters();
}
public AuthenticationService(
IEntitiesContext entities, IAppConfiguration config, IDiagnosticsService diagnostics,
IAuditingService auditing, IEnumerable<Authenticator> providers, ICredentialBuilder credentialBuilder,
ICredentialValidator credentialValidator, IDateTimeProvider dateTimeProvider, ITelemetryService telemetryService,
IContentObjectService contentObjectService)
{
InitCredentialFormatters();
Entities = entities ?? throw new ArgumentNullException(nameof(entities));
_config = config ?? throw new ArgumentNullException(nameof(config));
_trace = diagnostics?.SafeGetSource("AuthenticationService") ?? throw new ArgumentNullException(nameof(diagnostics));
Auditing = auditing ?? throw new ArgumentNullException(nameof(auditing)); ;
Authenticators = providers?.ToDictionary(p => p.Name, StringComparer.OrdinalIgnoreCase) ?? throw new ArgumentNullException(nameof(providers));
_credentialBuilder = credentialBuilder ?? throw new ArgumentNullException(nameof(credentialBuilder));
_credentialValidator = credentialValidator ?? throw new ArgumentNullException(nameof(credentialValidator));
_dateTimeProvider = dateTimeProvider ?? throw new ArgumentNullException(nameof(dateTimeProvider));
_telemetryService = telemetryService ?? throw new ArgumentNullException(nameof(telemetryService));
_contentObjectService = contentObjectService ?? throw new ArgumentNullException(nameof(contentObjectService));
}
public IEntitiesContext Entities { get; private set; }
public IDictionary<string, Authenticator> Authenticators { get; private set; }
public IAuditingService Auditing { get; private set; }
private void InitCredentialFormatters()
{
_credentialFormatters = new Dictionary<string, Func<string, string>>(StringComparer.OrdinalIgnoreCase) {
{ "password", _ => Strings.CredentialType_Password },
{ "apikey", _ => Strings.CredentialType_ApiKey },
{ "external", FormatExternalCredentialType }
};
}
public virtual async Task<PasswordAuthenticationResult> Authenticate(string userNameOrEmail, string password)
{
using (_trace.Activity("Authenticate"))
{
var user = FindByUserNameOrEmail(userNameOrEmail);
// Check if the user exists
if (user == null)
{
_trace.Information("No such user.");
await Auditing.SaveAuditRecordAsync(
new FailedAuthenticatedOperationAuditRecord(
userNameOrEmail, AuditedAuthenticatedOperationAction.FailedLoginNoSuchUser));
return new PasswordAuthenticationResult(PasswordAuthenticationResult.AuthenticationResult.BadCredentials);
}
if (user is Organization)
{
_trace.Information("Cannot authenticate organization account.");
await Auditing.SaveAuditRecordAsync(
new FailedAuthenticatedOperationAuditRecord(
userNameOrEmail, AuditedAuthenticatedOperationAction.FailedLoginUserIsOrganization));
return new PasswordAuthenticationResult(PasswordAuthenticationResult.AuthenticationResult.BadCredentials);
}
int remainingMinutes;
if (IsAccountLocked(user, out remainingMinutes))
{
_trace.Information($"Login failed. User account is locked for the next {remainingMinutes} minutes.");
return new PasswordAuthenticationResult(PasswordAuthenticationResult.AuthenticationResult.AccountLocked,
authenticatedUser: null, lockTimeRemainingMinutes: remainingMinutes);
}
// Validate the password
Credential matched;
if (!ValidatePasswordCredential(user.Credentials, password, out matched))
{
_trace.Information("Password validation failed.");
await UpdateFailedLoginAttempt(user);
await Auditing.SaveAuditRecordAsync(
new FailedAuthenticatedOperationAuditRecord(
userNameOrEmail, AuditedAuthenticatedOperationAction.FailedLoginInvalidPassword));
return new PasswordAuthenticationResult(PasswordAuthenticationResult.AuthenticationResult.BadCredentials);
}
var passwordCredentials = user
.Credentials
.Where(c => c.IsPassword())
.ToList();
if (passwordCredentials.Count > 1 ||
!passwordCredentials.Any(c => string.Equals(c.Type, CredentialBuilder.LatestPasswordType, StringComparison.OrdinalIgnoreCase)))
{
await MigrateCredentials(user, passwordCredentials, password);
}
// Reset failed login count upon successful login
await UpdateSuccessfulLoginAttempt(user);
// Return the result
_trace.Verbose("User successfully authenticated with '" + matched.Type + "' credential");
return new PasswordAuthenticationResult(PasswordAuthenticationResult.AuthenticationResult.Success, new AuthenticatedUser(user, matched));
}
}
public virtual async Task<AuthenticatedUser> Authenticate(string apiKey)
{
return await AuthenticateInternal(
FindMatchingApiKey,
new Credential { Type = CredentialTypes.ApiKey.Prefix, Value = apiKey });
}
public virtual async Task<AuthenticatedUser> Authenticate(Credential credential)
{
return await AuthenticateInternal(FindMatchingCredential, credential);
}
private async Task<AuthenticatedUser> AuthenticateInternal(Func<Credential, Credential> matchCredential, Credential credential)
{
if (credential.IsPassword())
{
// Password credentials cannot be used this way.
throw new ArgumentException(Strings.PasswordCredentialsCannotBeUsedHere, nameof(credential));
}
using (_trace.Activity("Authenticate Credential: " + credential.Type))
{
var matched = matchCredential(credential);
if (matched == null)
{
_trace.Information("No user matches credential of type: " + credential.Type);
await Auditing.SaveAuditRecordAsync(
new FailedAuthenticatedOperationAuditRecord(null,
AuditedAuthenticatedOperationAction.FailedLoginNoSuchUser,
attemptedCredential: credential));
return null;
}
if (matched.User is Organization)
{
_trace.Information("Cannot authenticate organization account.");
await Auditing.SaveAuditRecordAsync(
new FailedAuthenticatedOperationAuditRecord(null,
AuditedAuthenticatedOperationAction.FailedLoginUserIsOrganization,
attemptedCredential: credential));
return null;
}
if (matched.HasExpired)
{
_trace.Verbose("Credential of type '" + matched.Type + "' has expired on " + matched.Expires.Value.ToString("O", CultureInfo.InvariantCulture));
return null;
}
if (matched.IsApiKey() &&
!matched.IsScopedApiKey() &&
!matched.HasBeenUsedInLastDays(_config.ExpirationInDaysForApiKeyV1))
{
// API key credential was last used a long, long time ago - expire it
await Auditing.SaveAuditRecordAsync(
new UserAuditRecord(matched.User, AuditedUserAction.ExpireCredential, matched));
matched.Expires = _dateTimeProvider.UtcNow;
await Entities.SaveChangesAsync();
_trace.Verbose(
"Credential of type '" + matched.Type
+ "' was last used on " + matched.LastUsed.Value.ToString("O", CultureInfo.InvariantCulture)
+ " and has now expired.");
return null;
}
// update last used timestamp
matched.LastUsed = _dateTimeProvider.UtcNow;
await Entities.SaveChangesAsync();
_trace.Verbose("User successfully authenticated with '" + matched.Type + "' credential");
return new AuthenticatedUser(matched.User, matched);
}
}
public virtual async Task CreateSessionAsync(IOwinContext owinContext, AuthenticatedUser user)
{
// Create a claims identity for the session
ClaimsIdentity identity = CreateIdentity(user.User, AuthenticationTypes.LocalUser, await GetDiscontinuedLoginClaims(user));
// Issue the session token and clean up the external token if present
owinContext.Authentication.SignIn(identity);
owinContext.Authentication.SignOut(AuthenticationTypes.External);
// Write an audit record
await Auditing.SaveAuditRecordAsync(
new UserAuditRecord(user.User, AuditedUserAction.Login, user.CredentialUsed));
}
private async Task<Claim[]> GetDiscontinuedLoginClaims(AuthenticatedUser user)
{
await _contentObjectService.Refresh();
return _contentObjectService.LoginDiscontinuationConfiguration.IsLoginDiscontinued(user) ?
new[] { new Claim(NuGetClaims.DiscontinuedLogin, NuGetClaims.DiscontinuedLoginValue) } :
new Claim[0];
}
public virtual async Task<AuthenticatedUser> Register(string username, string emailAddress, Credential credential)
{
if (_config.FeedOnlyMode)
{
throw new FeedOnlyModeException(FeedOnlyModeException.FeedOnlyModeError);
}
var existingUser = Entities.Users
.FirstOrDefault(u => u.Username == username || u.EmailAddress == emailAddress);
if (existingUser != null)
{
if (string.Equals(existingUser.Username, username, StringComparison.OrdinalIgnoreCase))
{
throw new EntityException(Strings.UsernameNotAvailable, username);
}
else
{
throw new EntityException(Strings.EmailAddressBeingUsed, emailAddress);
}
}
var newUser = new User(username)
{
EmailAllowed = true,
UnconfirmedEmailAddress = emailAddress,
EmailConfirmationToken = CryptographyService.GenerateToken(),
NotifyPackagePushed = true,
CreatedUtc = _dateTimeProvider.UtcNow
};
// Add a credential for the password
newUser.Credentials.Add(credential);
if (!_config.ConfirmEmailAddresses)
{
newUser.ConfirmEmailAddress();
}
// Write an audit record
await Auditing.SaveAuditRecordAsync(new UserAuditRecord(newUser, AuditedUserAction.Register, credential));
Entities.Users.Add(newUser);
await Entities.SaveChangesAsync();
_telemetryService.TrackNewUserRegistrationEvent(newUser, credential);
return new AuthenticatedUser(newUser, credential);
}
public virtual Task ReplaceCredential(string username, Credential credential)
{
var user = Entities
.Users
.Include(u => u.Credentials)
.SingleOrDefault(u => u.Username == username);
if (user == null)
{
throw new InvalidOperationException(Strings.UserNotFound);
}
return ReplaceCredential(user, credential);
}
public virtual async Task<bool> TryReplaceCredential(User user, Credential credential)
{
if (user == null || credential == null)
{
return false;
}
// Check user credentials for existing cred for optimization to avoid expensive DB query
if (!user.HasCredential(credential) && FindMatchingCredential(credential) != null)
{
// Existing credential for a registered account
return false;
}
try
{
await ReplaceCredential(user, credential);
return true;
}
catch (InvalidOperationException)
{
// ReplaceCredential could throw InvalidOperationException if the user is an Organization.
// We shouldn't get into this situation ideally. Just being thorough.
return false;
}
}
public virtual async Task ReplaceCredential(User user, Credential credential)
{
await ReplaceCredentialInternal(user, credential);
await Entities.SaveChangesAsync();
}
public virtual async Task<Credential> ResetPasswordWithToken(string username, string token, string newPassword)
{
if (string.IsNullOrEmpty(newPassword))
{
throw new ArgumentNullException(nameof(newPassword));
}
var user = Entities
.Users
.Include(u => u.Credentials)
.SingleOrDefault(u => u.Username == username);
if (user != null && string.Equals(user.PasswordResetToken, token, StringComparison.Ordinal) && !user.PasswordResetTokenExpirationDate.IsInThePast())
{
if (!user.Confirmed)
{
throw new InvalidOperationException(Strings.UserIsNotYetConfirmed);
}
var cred = _credentialBuilder.CreatePasswordCredential(newPassword);
await ReplaceCredentialInternal(user, cred);
user.PasswordResetToken = null;
user.PasswordResetTokenExpirationDate = null;
user.FailedLoginCount = 0;
user.LastFailedLoginUtc = null;
await Entities.SaveChangesAsync();
return cred;
}
return null;
}
public virtual async Task<PasswordResetResult> GeneratePasswordResetToken(string usernameOrEmail, int expirationInMinutes)
{
if (String.IsNullOrEmpty(usernameOrEmail))
{
throw new ArgumentNullException(nameof(usernameOrEmail));
}
if (expirationInMinutes < 1)
{
throw new ArgumentException(
Strings.TokenExpirationShouldGiveUser1MinuteToChangePassword, nameof(expirationInMinutes));
}
var user = FindByUserNameOrEmail(usernameOrEmail);
if (user == null)
{
return new PasswordResetResult(PasswordResetResultType.UserNotFound, user: null);
}
var resultType = await GeneratePasswordResetToken(user, expirationInMinutes);
return new PasswordResetResult(resultType, user);
}
public virtual async Task<PasswordResetResultType> GeneratePasswordResetToken(User user, int expirationInMinutes)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
if (expirationInMinutes < 1)
{
throw new ArgumentException(
Strings.TokenExpirationShouldGiveUser1MinuteToChangePassword, nameof(expirationInMinutes));
}
if (!user.Confirmed)
{
return PasswordResetResultType.UserNotConfirmed;
}
if (!string.IsNullOrEmpty(user.PasswordResetToken) && !user.PasswordResetTokenExpirationDate.IsInThePast())
{
return PasswordResetResultType.Success;
}
user.PasswordResetToken = CryptographyService.GenerateToken();
user.PasswordResetTokenExpirationDate = _dateTimeProvider.UtcNow.AddMinutes(expirationInMinutes);
var passwordCredential = user.Credentials.FirstOrDefault(
credential => credential.Type.StartsWith(CredentialTypes.Password.Prefix, StringComparison.OrdinalIgnoreCase));
UserAuditRecord auditRecord;
if (passwordCredential == null)
{
auditRecord = new UserAuditRecord(user, AuditedUserAction.RequestPasswordReset);
}
else
{
auditRecord = new UserAuditRecord(user, AuditedUserAction.RequestPasswordReset, passwordCredential);
}
await Auditing.SaveAuditRecordAsync(auditRecord);
await Entities.SaveChangesAsync();
return PasswordResetResultType.Success;
}
public virtual async Task<bool> ChangePassword(User user, string oldPassword, string newPassword)
{
var hasPassword = user.Credentials.Any(
c => c.Type.StartsWith(CredentialTypes.Password.Prefix, StringComparison.OrdinalIgnoreCase));
Credential _;
if (hasPassword && !ValidatePasswordCredential(user.Credentials, oldPassword, out _))
{
// Invalid old password!
return false;
}
// Replace/Set password credential
var passwordCredential = _credentialBuilder.CreatePasswordCredential(newPassword);
await ReplaceCredentialInternal(user, passwordCredential);
// Save changes
await Entities.SaveChangesAsync();
return true;
}
public virtual ActionResult Challenge(string providerName, string redirectUrl)
{
Authenticator provider;
if (!Authenticators.TryGetValue(providerName, out provider))
{
throw new InvalidOperationException(string.Format(
CultureInfo.CurrentCulture,
Strings.UnknownAuthenticationProvider,
providerName));
}
if (!provider.BaseConfig.Enabled)
{
throw new InvalidOperationException(string.Format(
CultureInfo.CurrentCulture,
Strings.AuthenticationProviderDisabled,
providerName));
}
return provider.Challenge(redirectUrl);
}
public virtual async Task AddCredential(User user, Credential credential)
{
if (user is Organization)
{
throw new InvalidOperationException(Strings.OrganizationsCannotCreateCredentials);
}
await Auditing.SaveAuditRecordAsync(new UserAuditRecord(user, AuditedUserAction.AddCredential, credential));
user.Credentials.Add(credential);
await Entities.SaveChangesAsync();
_telemetryService.TrackNewCredentialCreated(user, credential);
}
public virtual CredentialViewModel DescribeCredential(Credential credential)
{
var kind = GetCredentialKind(credential.Type);
Authenticator authenticator = null;
if (kind == CredentialKind.External)
{
if (string.IsNullOrEmpty(credential.TenantId))
{
string providerName = credential.Type.Split('.')[1];
Authenticators.TryGetValue(providerName, out authenticator);
}
else
{
authenticator = Authenticators
.Values
.FirstOrDefault(provider => provider.Name.Equals(AzureActiveDirectoryV2Authenticator.DefaultAuthenticationType, StringComparison.OrdinalIgnoreCase));
}
}
var credentialViewModel = new CredentialViewModel
{
Key = credential.Key,
Type = credential.Type,
TypeCaption = FormatCredentialType(credential.Type),
Identity = credential.Identity,
Created = credential.Created,
Expires = credential.Expires,
Kind = kind,
AuthUI = authenticator?.GetUI(),
Description = credential.Description,
Scopes = credential.Scopes.Select(s => new ScopeViewModel(
s.Owner?.Username ?? credential.User.Username,
s.Subject,
NuGetScopes.Describe(s.AllowedAction)))
.ToList(),
ExpirationDuration = credential.ExpirationTicks != null ? new TimeSpan?(new TimeSpan(credential.ExpirationTicks.Value)) : null
};
credentialViewModel.HasExpired = credential.HasExpired ||
(credentialViewModel.IsNonScopedApiKey &&
!credential.HasBeenUsedInLastDays(_config.ExpirationInDaysForApiKeyV1));
credentialViewModel.Description = credentialViewModel.IsNonScopedApiKey
? Strings.NonScopedApiKeyDescription : credentialViewModel.Description;
return credentialViewModel;
}
public virtual async Task RemoveCredential(User user, Credential cred)
{
await Auditing.SaveAuditRecordAsync(new UserAuditRecord(user, AuditedUserAction.RemoveCredential, cred));
user.Credentials.Remove(cred);
Entities.Credentials.Remove(cred);
await Entities.SaveChangesAsync();
}
public virtual async Task EditCredentialScopes(User user, Credential cred, ICollection<Scope> newScopes)
{
foreach (var oldScope in cred.Scopes.ToArray())
{
Entities.Scopes.Remove(oldScope);
}
cred.Scopes = newScopes;
await Entities.SaveChangesAsync();
await Auditing.SaveAuditRecordAsync(new UserAuditRecord(user, AuditedUserAction.EditCredential, cred));
}
public virtual async Task<AuthenticateExternalLoginResult> ReadExternalLoginCredential(IOwinContext context)
{
var result = await context.Authentication.AuthenticateAsync(AuthenticationTypes.External);
if (result?.Identity?.Claims == null)
{
_trace.Information("No external login found.");
return new AuthenticateExternalLoginResult();
}
var externalIdentity = result.Identity;
Authenticator authenticator = Authenticators
.Values
.FirstOrDefault(a => a.IsProviderForIdentity(externalIdentity));
if (authenticator == null)
{
_trace.Error($"No authenticator found for identity: {externalIdentity.AuthenticationType}");
return new AuthenticateExternalLoginResult();
}
try
{
var userInfo = authenticator.GetIdentityInformation(externalIdentity);
var emailSuffix = userInfo.Email == null ? string.Empty : (" <" + userInfo.Email + ">");
var identity = userInfo.Name + emailSuffix;
return new AuthenticateExternalLoginResult()
{
Authentication = null,
ExternalIdentity = externalIdentity,
Authenticator = authenticator,
Credential = _credentialBuilder.CreateExternalCredential(userInfo.AuthenticationType, userInfo.Identifier, identity, userInfo.TenantId)
};
}
catch (Exception ex)
{
_trace.Error(ex.Message);
return new AuthenticateExternalLoginResult();
}
}
public virtual async Task<AuthenticateExternalLoginResult> AuthenticateExternalLogin(IOwinContext context)
{
var result = await ReadExternalLoginCredential(context);
// Authenticate!
if (result.Credential != null)
{
result.Authentication = await Authenticate(result.Credential);
}
return result;
}
public static ClaimsIdentity CreateIdentity(User user, string authenticationType, params Claim[] additionalClaims)
{
var claims = Enumerable.Concat(new[] {
new Claim(ClaimsIdentity.DefaultNameClaimType, user.Username),
new Claim(ClaimTypes.AuthenticationMethod, authenticationType),
// Needed for anti-forgery token, also good practice to have a unique identifier claim
new Claim(ClaimTypes.NameIdentifier, user.Username)
}, user.Roles.Select(r => new Claim(ClaimsIdentity.DefaultRoleClaimType, r.Name)));
if (additionalClaims.Length > 0)
{
claims = Enumerable.Concat(claims, additionalClaims);
}
ClaimsIdentity identity = new ClaimsIdentity(
claims,
authenticationType,
nameType: ClaimsIdentity.DefaultNameClaimType,
roleType: ClaimsIdentity.DefaultRoleClaimType);
return identity;
}
private async Task ReplaceCredentialInternal(User user, Credential credential)
{
if (user is Organization)
{
throw new InvalidOperationException(Strings.OrganizationsCannotCreateCredentials);
}
string replaceCredPrefix = null;
if (credential.IsPassword())
{
replaceCredPrefix = CredentialTypes.Password.Prefix;
}
else if (credential.IsExternal())
{
replaceCredPrefix = CredentialTypes.External.Prefix;
}
Func<Credential, bool> replacingPredicate;
if (!string.IsNullOrEmpty(replaceCredPrefix))
{
replacingPredicate = cred => cred.Type.StartsWith(replaceCredPrefix, StringComparison.OrdinalIgnoreCase);
}
else
{
replacingPredicate = cred => cred.Type.Equals(credential.Type, StringComparison.OrdinalIgnoreCase);
}
var toRemove = user.Credentials
.Where(replacingPredicate)
.ToList();
foreach (var cred in toRemove)
{
user.Credentials.Remove(cred);
Entities.DeleteOnCommit(cred);
}
if (toRemove.Any())
{
await Auditing.SaveAuditRecordAsync(new UserAuditRecord(
user, AuditedUserAction.RemoveCredential, toRemove));
}
user.Credentials.Add(credential);
await Auditing.SaveAuditRecordAsync(new UserAuditRecord(
user, AuditedUserAction.AddCredential, credential));
}
private static CredentialKind GetCredentialKind(string type)
{
if (CredentialTypes.IsApiKey(type))
{
return CredentialKind.Token;
}
else if (CredentialTypes.IsPassword(type))
{
return CredentialKind.Password;
}
return CredentialKind.External;
}
private string FormatCredentialType(string credentialType)
{
string[] splitted = credentialType.Split('.');
if (splitted.Length < 2)
{
return credentialType;
}
string prefix = splitted[0];
string subtype = credentialType.Substring(splitted[0].Length + 1);
Func<string, string> formatter;
if (!_credentialFormatters.TryGetValue(prefix, out formatter))
{
return credentialType;
}
return formatter(subtype);
}
private string FormatExternalCredentialType(string externalType)
{
Authenticator authenticator;
if (!Authenticators.TryGetValue(externalType, out authenticator))
{
return externalType;
}
var ui = authenticator.GetUI();
return ui == null ? authenticator.Name : ui.AccountNoun;
}
private Credential FindMatchingCredential(Credential credential)
{
var results = Entities
.Set<Credential>()
.Include(u => u.User)
.Include(u => u.User.Roles)
.Include(u => u.Scopes)
.Where(c => c.Type == credential.Type && c.Value == credential.Value)
.ToList();
return ValidateFoundCredentials(results, credential.Type);
}
private Credential FindMatchingApiKey(Credential apiKeyCredential)
{
var allCredentials = Entities
.Set<Credential>()
.Include(u => u.User)
.Include(u => u.User.Roles)
.Include(u => u.Scopes);
var results = _credentialValidator.GetValidCredentialsForApiKey(allCredentials, apiKeyCredential.Value);
return ValidateFoundCredentials(results, Strings.CredentialType_ApiKey);
}
private Credential ValidateFoundCredentials(IList<Credential> results, string credentialType)
{
if (results.Count > 1)
{
// Don't put the credential itself in trace, but do put the key for lookup later.
string message = string.Format(
CultureInfo.CurrentCulture,
Strings.MultipleMatchingCredentials,
credentialType,
results.First().Key);
_trace.Error(message);
throw new InvalidOperationException(message);
}
return results.FirstOrDefault();
}
private User FindByUserNameOrEmail(string userNameOrEmail)
{
var users = Entities
.Users
.Include(u => u.Credentials)
.Include(u => u.Roles);
var user = users.SingleOrDefault(u => u.Username == userNameOrEmail);
if (user == null)
{
var allMatches = users
.Where(u => u.EmailAddress == userNameOrEmail)
.Take(2)
.ToList();
if (allMatches.Count == 1)
{
user = allMatches[0];
}
else
{
// If multiple matches, leave it null to signal no unique email address
_trace.Warning($"Multiple user accounts with a single email address were found. Count: {allMatches.Count}");
}
}
return user;
}
private async Task UpdateFailedLoginAttempt(User user)
{
user.FailedLoginCount += 1;
user.LastFailedLoginUtc = _dateTimeProvider.UtcNow;
await Entities.SaveChangesAsync();
}
private async Task UpdateSuccessfulLoginAttempt(User user)
{
user.FailedLoginCount = 0;
user.LastFailedLoginUtc = null;
await Entities.SaveChangesAsync();
}
private bool IsAccountLocked(User user, out int remainingMinutes)
{
if (user.FailedLoginCount > 0)
{
var currentTime = _dateTimeProvider.UtcNow;
var unlockTime = CalculateAccountUnlockTime(user.FailedLoginCount, user.LastFailedLoginUtc.Value);
if (unlockTime > currentTime)
{
remainingMinutes = (int)Math.Ceiling((unlockTime - currentTime).TotalMinutes);
return true;
}
}
remainingMinutes = 0;
return false;
}
private DateTime CalculateAccountUnlockTime(int failedLoginCount, DateTime lastFailedLogin)
{
int lockoutPeriodInMinutes = (int)Math.Pow(AccountLockoutMultiplierInMinutes, (int)((double)failedLoginCount / AllowedLoginAttempts) - 1);
return lastFailedLogin + TimeSpan.FromMinutes(lockoutPeriodInMinutes);
}
public virtual bool ValidatePasswordCredential(IEnumerable<Credential> creds, string password, out Credential matched)
{
matched = creds.FirstOrDefault(c => _credentialValidator.ValidatePasswordCredential(c, password));
return matched != null;
}
private async Task MigrateCredentials(User user, List<Credential> creds, string password)
{
// Authenticate already validated that user is not an Organization, so no need to replicate here.
var toRemove = creds.Where(c =>
!string.Equals(
c.Type,
CredentialBuilder.LatestPasswordType,
StringComparison.OrdinalIgnoreCase))
.ToList();
// Remove any non latest credentials
foreach (var cred in toRemove)
{
creds.Remove(cred);
user.Credentials.Remove(cred);
Entities.DeleteOnCommit(cred);
}
await Auditing.SaveAuditRecordAsync(new UserAuditRecord(user, AuditedUserAction.RemoveCredential, toRemove));
// Now add one if there are no credentials left
if (creds.Count == 0)
{
var newCred = _credentialBuilder.CreatePasswordCredential(password);
await Auditing.SaveAuditRecordAsync(new UserAuditRecord(user, AuditedUserAction.AddCredential, newCred));
user.Credentials.Add(newCred);
}
// Save changes, if any
await Entities.SaveChangesAsync();
}
}
}