Search code examples
c#asp.net-mvcoauth-2.0google-oauthgoogle-api-dotnet-client

How to get email address of a user using Google Oauth .NET library


I would like to get the email address of a user after successful sign-in. Google Plus APIs will be depreciated by Google. Any other way to access just email address of the user? Using the below code, I'll have access access token and id_token of the user.

UserCredential credential =
                GoogleWebAuthorizationBroker.AuthorizeAsync(
                    new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                    , scopes
                    , userName
                    , CancellationToken.None
                    , new FileDataStore(fileDataStorePath)).Result;

Update: The following code worked.

           var gmailService = new Google.Apis.Gmail.v1.GmailService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName = "App name"
            });

            var gmailProfile = gmailService.Users.GetProfile("me").Execute();
            string EmailAddress = gmailProfile.EmailAddress;


Solution

  • Make sure that you have include the "email" scope as part of your scopes.

    create a service object.

    var service = new PeopleService(new BaseClientService.Initializer()
       {
        HttpClientInitializer = credential,
        ApplicationName = "Peopleservice Oauth2 Authentication Sample"
        });
    

    Then make a request to the people api.

    var results = service.People.Get("person/me").ExecuteAsync();