private async Task <IdUser> IntegrateExternalUser(string provider, string providerUserId, IEnumerable <Claim> claims, IdUser user = null) { if (user == null) { user = new IdUser(); _idUserDbContext.Add(user); await _userManager.UpdateSecurityStampAsync(user); } var claimsToRemove = _idUserDbContext.UserClaims.Where(claim => claim.UserId == user.Id && claim.Issuer == provider); _idUserDbContext.UserClaims.RemoveRange(claimsToRemove); await _idUserDbContext.SaveChangesAsync(); var claimsToUse = new List <IdUserClaim>(); foreach (var claim in claims) { if (claim.Type == ClaimTypes.Name) { claimsToUse.Add(new IdUserClaim { ClaimType = JwtClaimTypes.Name, ClaimValue = claim.Value, UserId = user.Id, Issuer = provider }); } else if (JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.ContainsKey(claim.Type)) { claimsToUse.Add(new IdUserClaim { ClaimType = JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap[claim.Type], ClaimValue = claim.Value, UserId = user.Id, Issuer = provider }); } else { claimsToUse.Add(new IdUserClaim { ClaimType = claim.Type, ClaimValue = claim.Value, UserId = user.Id, Issuer = provider }); } } // if no display name was provided, try to construct by first and/or last name if (!claimsToUse.Any(claim => claim.ClaimType == JwtClaimTypes.Name)) { var first = claimsToUse.FirstOrDefault(x => x.ClaimType == JwtClaimTypes.GivenName)?.ClaimValue; var last = claimsToUse.FirstOrDefault(x => x.ClaimType == JwtClaimTypes.FamilyName)?.ClaimValue; if (first != null && last != null) { claimsToUse.Add(new IdUserClaim { ClaimType = JwtClaimTypes.Name, ClaimValue = first + " " + last, UserId = user.Id, Issuer = provider }); } else if (first != null) { claimsToUse.Add(new IdUserClaim { ClaimType = JwtClaimTypes.Name, ClaimValue = first, UserId = user.Id, Issuer = provider }); } else if (last != null) { claimsToUse.Add(new IdUserClaim { ClaimType = JwtClaimTypes.Name, ClaimValue = last, UserId = user.Id, Issuer = provider }); } } claimsToUse.Add(new IdUserClaim { ClaimType = "ApiAccess", ClaimValue = "IdApi1", UserId = user.Id, Issuer = "local" }); claimsToUse.Add(new IdUserClaim { ClaimType = "ApiAccess", ClaimValue = "IdUserApi", UserId = user.Id, Issuer = "local" }); user.UserName = claimsToUse.FirstOrDefault(c => c.ClaimType == JwtClaimTypes.Name)?.ClaimValue ?? user.Id; user.NormalizedUserName = user.UserName; _idUserDbContext.AddRange(claimsToUse); var externalLogins = await _userManager.GetLoginsAsync(user); if (externalLogins == null || externalLogins.Count == 0) { await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, providerUserId, user.UserName)); } await _idUserDbContext.SaveChangesAsync(); return(user); }