In my application, the user would login into the application and then authorize facebook(by clicking a button in a secure area) to allow the application to get facebook posts etc. Here's the code that I have written to save the claims and authentication tokens with internal user account. I am however getting User "bc7e2d39-4e31-4012-8461-512c3df57b95" validation failed: DuplicateUserName.
error.
Previously I was getting a User security stamp cannot be null.
To workaround this issue, I had to specify the SecurityStamp when creating the applicationUser.
var applicationUser = new ApplicationUser { UserName = identityUser.Email, Email = identityUser.Email , SecurityStamp= Guid.NewGuid().ToString()};
Am I following the right approach? If not, would it be easier to directly insert records into the AspNetUserClaims, AspNetUserTokens tables for claims, authentication tokens, using Entity Framework core.
public async Task<IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (remoteError != null)
{
ErrorMessage = $"Error from external provider: {remoteError}";
return RedirectToPage("./Settings", new { ReturnUrl = returnUrl });
}
// Get the information about the user from the external login provider
var identityUser = await UserManager.GetUserAsync(User);
var externalLoginInfo = await SignInManager.GetExternalLoginInfoAsync();
if (externalLoginInfo == null)
{
ErrorMessage = "Error loading external login information during confirmation.";
return RedirectToPage("./Settings", new { ReturnUrl = returnUrl });
}
var applicationUser = new ApplicationUser { UserName = identityUser.Email, Email = identityUser.Email , SecurityStamp= Guid.NewGuid().ToString()};
var identityResult = await this.UserManager.AddLoginAsync(applicationUser, externalLoginInfo);
if (identityResult.Succeeded)
{
if (externalLoginInfo.Principal.HasClaim(c => c.Type == ClaimTypes.GivenName))
{
await this.UserManager.AddClaimAsync(applicationUser, externalLoginInfo.Principal.FindFirst(ClaimTypes.GivenName));
}
identityResult = await SignInManager.UpdateExternalAuthenticationTokensAsync(externalLoginInfo);
var authenticationProperties = new AuthenticationProperties();
authenticationProperties.StoreTokens(externalLoginInfo.AuthenticationTokens);
//authenticationProperties.IsPersistent = true;
#endregion
return LocalRedirect(returnUrl);
}
foreach (var error in identityResult.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
LoginProvider = externalLoginInfo.LoginProvider;
ReturnUrl = returnUrl;
return Page();
}
#endregion
}