Search code examples
asp.net-mvcasp.net-identity

How to get FirstName + LastName from the user's google account authenticated using Asp.Identity in MVC5 application


I have created a MVC 5 application, and I'm able to authenticate the user using Google External login which is an out of box feature. I have observed that by authenticating the user using google account, UserName and Email are stored in database with the same value(i.e., Email for both of them). How do i retreive FirstName, LastName, from the registered google account.


Solution

  • You can get this inside the ExternalLoginCallback method in AccountController (as you are using out of the box project template) as explained below.

        [AllowAnonymous]
        public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (loginInfo == null)
            {
                return RedirectToAction("Login");
            }
    
            if (loginInfo.Login.LoginProvider == "Google")
            {
                    var externalIdentity = AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
                    var emailClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email);
                    var lastNameClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname);
                    var givenNameClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName);
    
                    var email = emailClaim.Value;
                    var firstName = givenNameClaim.Value;
                    var lastname = lastNameClaim.Value;
            }
    
         }
    

    Hope this helps.