Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 327
Prithvi Avatar asked Jan 26 '15 02:01

Prithvi


People also ask

How will you implement authentication and authorization in ASP NET MVC application?

For form authentication the user needs to provide his credentials through a form. Windows Authentication is used in conjunction with IIS authentication. The Authentication is performed by IIS in one of three ways such as basic, digest, or Integrated Windows Authentication.

What is custom authentication in ASP NET?

For building custom authentication, we use membership provider class which is able to check the user credentials (username & password) and role provider class that is used to verify the user authorization based on his/her roles.


1 Answers

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.

like image 101
DSR Avatar answered Nov 06 '22 18:11

DSR