Access User Info using Google APIs for .NET

CodingIntrigue picture CodingIntrigue · Jan 23, 2014 · Viewed 12k times · Source

I'm using the Google APIs Preview (1.7.0) to authorize a user via OAuth2. I've been following the sample MVC code. This is my implementation of FlowMetadata:

private static readonly IAuthorizationCodeFlow flow = ...; // Implementation of tokens

public static async Task<Google.Apis.Auth.OAuth2.Web.AuthorizationCodeWebApp.AuthResult> GetCredentials(Controller controller, CancellationToken cancellationToken) {
    var result = await new AuthorizationCodeMvcApp(controller, new Models.Generic.AppFlowMetadata()).AuthorizeAsync(cancellationToken);
    if (result.Credential != null)
    {
         // Struggling here. How do I make a request to get the e-mail address?
    }
}

I now have a valid UserCredential and therefore Access Token, but I cannot find any managed APIs for accessing the user info. I did find this question, but this appears to assume I am just making raw requests, rather than using the official library.

How can I get the user's e-mail address?

Answer

peleyal picture peleyal · Jan 27, 2014

You should do the following:

  1. In addition to Google.Apis.Auth NuGet package you should install the following page: https://www.nuget.org/packages/Google.Apis.Oauth2.v2

  2. Add Google.Apis.Oauth2.v2.Oauth2Service.Scope.UserinfoProfile and also Google.Apis.Oauth2.v2.Oauth2Service.Scope.UserinfoEmail to the scopes list (When you initialize the AppFlowMetadata).

  3. Now, add the following code:

if (result.Credential != null)
{
    var oauthSerivce = new Google.Apis.Oauth2.v2.Oauth2Service(
        new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "OAuth 2.0 Sample",
        });

    var userInfo = await oauthSerivce.Userinfo.Get().ExecuteAsync();
    // You can use userInfo.Email, Gender, FamilyName, ... 
}