Search code examples
identityserver4openid-connectasp.net-core-identity

How to deal with External authentication for already existing local user or new user


I using ASP.Net Core 3 Identity with Identity Server 4 for authentication ...

On the AspNetIdentity template the External Authentication Controller Callback method calls the AutoProvisionUserAsync method which has the following code:

  var email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ??
     claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;
  if (email != null) {
    filtered.Add(new Claim(JwtClaimTypes.Email, email));
  }

  var user = new User {
    UserName = Guid.NewGuid().ToString(),
  };

  var identityResult = await _userManager.CreateAsync(user);

Basically it creates a user with a Guid as Username ...

In my database I am using Email as Username ... Is there any reason to use a Guid?

I suppose most External authentication services (Google, Facebook, etc) provides an Email.

So my idea would be:

  1. Check if there is an User in the database already with that email.
  2. If no User exists create one with the email obtained from the External authentication service. Also add the external authentication to the User in the database;
  3. If there is a User with the email in the database check if it has that External Login. If the user does not have the external login register and add it.

Does this make sense?


Solution

    1. Check if there is an User in the database already with that email.

    On callback, first call is to FindUserFromExternalProviderAsync, it search users using nameIdentifier, then if not found there is call to AutoProvisionUserAsync

    Basically it creates a user with a Guid as Username ... In my database I am using Email as Username ... Is there any reason to use a Guid?

    The ApplicationUser's base class is IdentityUser, IdentityUser has a prop for ID and one for email by design. thats why most of libraries take advantage of having GUID as ID in addition of email for extensibility. You can use the email for ID if you like to.