This repository has been archived by the owner on Dec 14, 2017. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
IdentityServer3.AspNetIdentity.cs
444 lines (382 loc) · 17.9 KB
/
IdentityServer3.AspNetIdentity.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
/*
* Copyright 2015 Dominick Baier, Brock Allen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using IdentityServer3.Core.Models;
using IdentityServer3.Core.Services;
using IdentityServer3.Core.Extensions;
using IdentityServer3.Core;
using IdentityModel;
using IdentityServer3.Core.Services.Default;
namespace IdentityServer3.AspNetIdentity
{
public class AspNetIdentityUserService<TUser, TKey> : UserServiceBase
where TUser : class, Microsoft.AspNet.Identity.IUser<TKey>, new()
where TKey : IEquatable<TKey>
{
public string DisplayNameClaimType { get; set; }
public bool EnableSecurityStamp { get; set; }
protected readonly Microsoft.AspNet.Identity.UserManager<TUser, TKey> userManager;
protected readonly Func<string, TKey> ConvertSubjectToKey;
public AspNetIdentityUserService(Microsoft.AspNet.Identity.UserManager<TUser, TKey> userManager, Func<string, TKey> parseSubject = null)
{
if (userManager == null) throw new ArgumentNullException("userManager");
this.userManager = userManager;
if (parseSubject != null)
{
ConvertSubjectToKey = parseSubject;
}
else
{
var keyType = typeof (TKey);
if (keyType == typeof (string)) ConvertSubjectToKey = subject => (TKey) ParseString(subject);
else if (keyType == typeof (int)) ConvertSubjectToKey = subject => (TKey) ParseInt(subject);
else if (keyType == typeof (uint)) ConvertSubjectToKey = subject => (TKey) ParseUInt32(subject);
else if (keyType == typeof (long)) ConvertSubjectToKey = subject => (TKey) ParseLong(subject);
else if (keyType == typeof (Guid)) ConvertSubjectToKey = subject => (TKey) ParseGuid(subject);
else
{
throw new InvalidOperationException("Key type not supported");
}
}
EnableSecurityStamp = true;
}
object ParseString(string sub)
{
return sub;
}
object ParseInt(string sub)
{
int key;
if (!Int32.TryParse(sub, out key)) return 0;
return key;
}
object ParseUInt32(string sub)
{
uint key;
if (!UInt32.TryParse(sub, out key)) return 0;
return key;
}
object ParseLong(string sub)
{
long key;
if (!Int64.TryParse(sub, out key)) return 0;
return key;
}
object ParseGuid(string sub)
{
Guid key;
if (!Guid.TryParse(sub, out key)) return Guid.Empty;
return key;
}
public override async Task GetProfileDataAsync(ProfileDataRequestContext ctx)
{
var subject = ctx.Subject;
var requestedClaimTypes = ctx.RequestedClaimTypes;
if (subject == null) throw new ArgumentNullException("subject");
TKey key = ConvertSubjectToKey(subject.GetSubjectId());
var acct = await userManager.FindByIdAsync(key);
if (acct == null)
{
throw new ArgumentException("Invalid subject identifier");
}
var claims = await GetClaimsFromAccount(acct);
if (requestedClaimTypes != null && requestedClaimTypes.Any())
{
claims = claims.Where(x => requestedClaimTypes.Contains(x.Type));
}
ctx.IssuedClaims = claims;
}
protected virtual async Task<IEnumerable<Claim>> GetClaimsFromAccount(TUser user)
{
var claims = new List<Claim>{
new Claim(Constants.ClaimTypes.Subject, user.Id.ToString()),
new Claim(Constants.ClaimTypes.PreferredUserName, user.UserName),
};
if (userManager.SupportsUserEmail)
{
var email = await userManager.GetEmailAsync(user.Id);
if (!String.IsNullOrWhiteSpace(email))
{
claims.Add(new Claim(Constants.ClaimTypes.Email, email));
var verified = await userManager.IsEmailConfirmedAsync(user.Id);
claims.Add(new Claim(Constants.ClaimTypes.EmailVerified, verified ? "true" : "false"));
}
}
if (userManager.SupportsUserPhoneNumber)
{
var phone = await userManager.GetPhoneNumberAsync(user.Id);
if (!String.IsNullOrWhiteSpace(phone))
{
claims.Add(new Claim(Constants.ClaimTypes.PhoneNumber, phone));
var verified = await userManager.IsPhoneNumberConfirmedAsync(user.Id);
claims.Add(new Claim(Constants.ClaimTypes.PhoneNumberVerified, verified ? "true" : "false"));
}
}
if (userManager.SupportsUserClaim)
{
claims.AddRange(await userManager.GetClaimsAsync(user.Id));
}
if (userManager.SupportsUserRole)
{
var roleClaims =
from role in await userManager.GetRolesAsync(user.Id)
select new Claim(Constants.ClaimTypes.Role, role);
claims.AddRange(roleClaims);
}
return claims;
}
protected virtual async Task<string> GetDisplayNameForAccountAsync(TKey userID)
{
var user = await userManager.FindByIdAsync(userID);
var claims = await GetClaimsFromAccount(user);
Claim nameClaim = null;
if (DisplayNameClaimType != null)
{
nameClaim = claims.FirstOrDefault(x => x.Type == DisplayNameClaimType);
}
if (nameClaim == null) nameClaim = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.Name);
if (nameClaim == null) nameClaim = claims.FirstOrDefault(x => x.Type == ClaimTypes.Name);
if (nameClaim != null) return nameClaim.Value;
return user.UserName;
}
protected async virtual Task<TUser> FindUserAsync(string username)
{
return await userManager.FindByNameAsync(username);
}
protected virtual Task<AuthenticateResult> PostAuthenticateLocalAsync(TUser user, SignInMessage message)
{
return Task.FromResult<AuthenticateResult>(null);
}
public override async Task AuthenticateLocalAsync(LocalAuthenticationContext ctx)
{
var username = ctx.UserName;
var password = ctx.Password;
var message = ctx.SignInMessage;
ctx.AuthenticateResult = null;
if (userManager.SupportsUserPassword)
{
var user = await FindUserAsync(username);
if (user != null)
{
if (userManager.SupportsUserLockout &&
await userManager.IsLockedOutAsync(user.Id))
{
return;
}
if (await userManager.CheckPasswordAsync(user, password))
{
if (userManager.SupportsUserLockout)
{
await userManager.ResetAccessFailedCountAsync(user.Id);
}
var result = await PostAuthenticateLocalAsync(user, message);
if (result == null)
{
var claims = await GetClaimsForAuthenticateResult(user);
result = new AuthenticateResult(user.Id.ToString(), await GetDisplayNameForAccountAsync(user.Id), claims);
}
ctx.AuthenticateResult = result;
}
else if (userManager.SupportsUserLockout)
{
await userManager.AccessFailedAsync(user.Id);
}
}
}
}
protected virtual async Task<IEnumerable<Claim>> GetClaimsForAuthenticateResult(TUser user)
{
List<Claim> claims = new List<Claim>();
if (EnableSecurityStamp && userManager.SupportsUserSecurityStamp)
{
var stamp = await userManager.GetSecurityStampAsync(user.Id);
if (!String.IsNullOrWhiteSpace(stamp))
{
claims.Add(new Claim("security_stamp", stamp));
}
}
return claims;
}
public override async Task AuthenticateExternalAsync(ExternalAuthenticationContext ctx)
{
var externalUser = ctx.ExternalIdentity;
var message = ctx.SignInMessage;
if (externalUser == null)
{
throw new ArgumentNullException("externalUser");
}
var user = await userManager.FindAsync(new Microsoft.AspNet.Identity.UserLoginInfo(externalUser.Provider, externalUser.ProviderId));
if (user == null)
{
ctx.AuthenticateResult = await ProcessNewExternalAccountAsync(externalUser.Provider, externalUser.ProviderId, externalUser.Claims);
}
else
{
ctx.AuthenticateResult = await ProcessExistingExternalAccountAsync(user.Id, externalUser.Provider, externalUser.ProviderId, externalUser.Claims);
}
}
protected virtual async Task<AuthenticateResult> ProcessNewExternalAccountAsync(string provider, string providerId, IEnumerable<Claim> claims)
{
var user = await TryGetExistingUserFromExternalProviderClaimsAsync(provider, claims);
if (user == null)
{
user = await InstantiateNewUserFromExternalProviderAsync(provider, providerId, claims);
if (user == null)
throw new InvalidOperationException("CreateNewAccountFromExternalProvider returned null");
var createResult = await userManager.CreateAsync(user);
if (!createResult.Succeeded)
{
return new AuthenticateResult(createResult.Errors.First());
}
}
var externalLogin = new Microsoft.AspNet.Identity.UserLoginInfo(provider, providerId);
var addExternalResult = await userManager.AddLoginAsync(user.Id, externalLogin);
if (!addExternalResult.Succeeded)
{
return new AuthenticateResult(addExternalResult.Errors.First());
}
var result = await AccountCreatedFromExternalProviderAsync(user.Id, provider, providerId, claims);
if (result != null) return result;
return await SignInFromExternalProviderAsync(user.Id, provider);
}
protected virtual Task<TUser> InstantiateNewUserFromExternalProviderAsync(string provider, string providerId, IEnumerable<Claim> claims)
{
var user = new TUser() { UserName = Guid.NewGuid().ToString("N") };
return Task.FromResult(user);
}
protected virtual Task<TUser> TryGetExistingUserFromExternalProviderClaimsAsync(string provider, IEnumerable<Claim> claims)
{
return Task.FromResult<TUser>(null);
}
protected virtual async Task<AuthenticateResult> AccountCreatedFromExternalProviderAsync(TKey userID, string provider, string providerId, IEnumerable<Claim> claims)
{
claims = await SetAccountEmailAsync(userID, claims);
claims = await SetAccountPhoneAsync(userID, claims);
return await UpdateAccountFromExternalClaimsAsync(userID, provider, providerId, claims);
}
protected virtual async Task<AuthenticateResult> SignInFromExternalProviderAsync(TKey userID, string provider)
{
var user = await userManager.FindByIdAsync(userID);
var claims = await GetClaimsForAuthenticateResult(user);
return new AuthenticateResult(
userID.ToString(),
await GetDisplayNameForAccountAsync(userID),
claims,
authenticationMethod: Constants.AuthenticationMethods.External,
identityProvider: provider);
}
protected virtual async Task<AuthenticateResult> UpdateAccountFromExternalClaimsAsync(TKey userID, string provider, string providerId, IEnumerable<Claim> claims)
{
var existingClaims = await userManager.GetClaimsAsync(userID);
var intersection = existingClaims.Intersect(claims, new ClaimComparer());
var newClaims = claims.Except(intersection, new ClaimComparer());
foreach (var claim in newClaims)
{
var result = await userManager.AddClaimAsync(userID, claim);
if (!result.Succeeded)
{
return new AuthenticateResult(result.Errors.First());
}
}
return null;
}
protected virtual async Task<AuthenticateResult> ProcessExistingExternalAccountAsync(TKey userID, string provider, string providerId, IEnumerable<Claim> claims)
{
return await SignInFromExternalProviderAsync(userID, provider);
}
protected virtual async Task<IEnumerable<Claim>> SetAccountEmailAsync(TKey userID, IEnumerable<Claim> claims)
{
var email = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.Email);
if (email != null)
{
var userEmail = await userManager.GetEmailAsync(userID);
if (userEmail == null)
{
// if this fails, then presumably the email is already associated with another account
// so ignore the error and let the claim pass thru
var result = await userManager.SetEmailAsync(userID, email.Value);
if (result.Succeeded)
{
var email_verified = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.EmailVerified);
if (email_verified != null && email_verified.Value == "true")
{
var token = await userManager.GenerateEmailConfirmationTokenAsync(userID);
await userManager.ConfirmEmailAsync(userID, token);
}
var emailClaims = new string[] { Constants.ClaimTypes.Email, Constants.ClaimTypes.EmailVerified };
return claims.Where(x => !emailClaims.Contains(x.Type));
}
}
}
return claims;
}
protected virtual async Task<IEnumerable<Claim>> SetAccountPhoneAsync(TKey userID, IEnumerable<Claim> claims)
{
var phone = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.PhoneNumber);
if (phone != null)
{
var userPhone = await userManager.GetPhoneNumberAsync(userID);
if (userPhone == null)
{
// if this fails, then presumably the phone is already associated with another account
// so ignore the error and let the claim pass thru
var result = await userManager.SetPhoneNumberAsync(userID, phone.Value);
if (result.Succeeded)
{
var phone_verified = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.PhoneNumberVerified);
if (phone_verified != null && phone_verified.Value == "true")
{
var token = await userManager.GenerateChangePhoneNumberTokenAsync(userID, phone.Value);
await userManager.ChangePhoneNumberAsync(userID, phone.Value, token);
}
var phoneClaims = new string[] { Constants.ClaimTypes.PhoneNumber, Constants.ClaimTypes.PhoneNumberVerified };
return claims.Where(x => !phoneClaims.Contains(x.Type));
}
}
}
return claims;
}
public override async Task IsActiveAsync(IsActiveContext ctx)
{
var subject = ctx.Subject;
if (subject == null) throw new ArgumentNullException("subject");
var id = subject.GetSubjectId();
TKey key = ConvertSubjectToKey(id);
var acct = await userManager.FindByIdAsync(key);
ctx.IsActive = false;
if (acct != null)
{
if (EnableSecurityStamp && userManager.SupportsUserSecurityStamp)
{
var security_stamp = subject.Claims.Where(x => x.Type == "security_stamp").Select(x => x.Value).SingleOrDefault();
if (security_stamp != null)
{
var db_security_stamp = await userManager.GetSecurityStampAsync(key);
if (db_security_stamp != security_stamp)
{
return;
}
}
}
ctx.IsActive = true;
}
}
}
}