David Thielen
David Thielen

Reputation: 32986

How do I get the phone number & address from a Google account in Identity Library

I am using the ASP.NET Core 6 Identity library. I added in logging in using my Google account and that works fine. I now want to add getting the account's phone number and address. This is failing.

In program.cs I set:

var auth = builder.Services.AddAuthentication();
var googleClientId = configMgr.GetValue<string>("Authentication:Google:ClientId");
var googleClientSecret = configMgr.GetValue<string>("Authentication:Google:ClientSecret");

// Add authentication services
if ((!string.IsNullOrEmpty(googleClientId)) && !string.IsNullOrEmpty(googleClientSecret))
{
    auth.AddGoogle(options =>
        {
            options.ClientId = googleClientId;
            options.ClientSecret = googleClientSecret;
             options.Scope.Add("https://www.googleapis.com/auth/user.phonenumbers.read");
             options.Scope.Add("https://www.googleapis.com/auth/user.addresses.read");
             options.ClaimActions.MapJsonKey(ClaimTypes.MobilePhone, "phoneNumber");
             options.ClaimActions.MapJsonKey(ClaimTypes.StreetAddress, "address");
        });
}

When I go to log in, Google does tell me that it wants my phone number and address and lets me decide if I want to pass them. I click the check box for both and submit the form.

Then in ExternalLogin.cshtml.cs, in the method

public async Task<IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null, [FromQuery] string following = null)
{
   var info = await _signInManager.GetExternalLoginInfoAsync();
   var phoneNumber = info.Principal.FindFirstValue(ClaimTypes.MobilePhone);
   var address = info.Principal.FindFirstValue(ClaimTypes.StreetAddress);
   // ...
}

Both phoneNumber and address are null. I looked at all claims and all it has is the nameidentifier, name, surname, givenname, & emailaddress.

My Google account at https://myaccount.google.com/personal-info does have a phone & address:

enter image description here

What am I missing?

Upvotes: 1

Views: 34

Answers (0)

Related Questions