Search code examples
c#asp.net-coreasp.net-core-mvcdapperasp.net-core-identity

ASP.NET Core Get UserId after ExternalLoginSignInAsync


I login my user via third part such as google in the following way:

var info = await _signInManager.GetExternalLoginInfoAsync();
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, false);

Should the above succeeds because they exist, how can I capture the userId of the user who logged in? The userId is the userId that sits in my database on the Users table, it won't be anything that comes from the third party login provider.

Is this possible? I can't seem to find any function or object that would let me retrieve it at this point. I thought maybe getting it out of the User Object, but to my understanding that comes from the HttpContext which at this point in time would not have the user registered as logged in, at least not until I refresh the page. I would also like to avoid redirecting to another page just for purposes of this.

Note: I am using Dapper and there is no trace of EF in my project. Not sure how much this will matter.


Solution

  • ExternalLoginSignInAsync internally calls

    var user = await UserManager.FindByLoginAsync(loginProvider, providerKey);
    

    So, you could do the same:

    var info = await _signInManager.GetExternalLoginInfoAsync();
    var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, false);
    
    if (result = IdentityResult.Success)
    {
        var user = await _userManager.FindByLoginAsync(info.LoginProvider, info.ProviderKey);
    }
    

    Always remember that ASP.NET Core is open-source, so most times the fastest is to just look at the default implementation.