12

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?

2
  • Can you post code of private static readonly IAuthorizationCodeFlow flow = ...; // Implementation of tokens. Actually i'm stuck at that point and not getting any solution. Here's link to my Question Commented Jul 19, 2017 at 13:22
  • right now i'm getting this issue. My Question Commented Jul 19, 2017 at 13:23

4 Answers 4

24
+500

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, ... 
}
Sign up to request clarification or add additional context in comments.

4 Comments

Great work. Only minor adjustment I made to your answer was to add the Google.Apis.Oauth2.v2.Oauth2Service.Scope.UserinfoEmail scope :)
What about credential?
@SebastiánRojas result.Credential
what is result? please dont just copy/paste. it will be helpful if someone can explain as well
2

Set your scopes to:

At: Google.Apis.Auth.OAuth2.Flows.AuthorizationCodeFlow.Scopes

And use this endpoint address: https://www.googleapis.com/oauth2/v1/userinfo?alt=json

That should help you to acquire the required information.

Comments

1

Here ,I edit my answere. Please look into this. On Default2.aspx page , I am displaying Session["username"] and Session["useremail"] value in label. I hope these will be help for you.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;

public partial class _Default : System.Web.UI.Page 
{

   protected void Page_Load(object sender, EventArgs e)
   {

       openIdAuth();

   }

   protected void openIdAuth()
  {
       OpenIdAjaxRelyingParty rp = new OpenIdAjaxRelyingParty();
       var response = rp.GetResponse();

       if (response != null)
       {
         switch (response.Status)
         {
            case AuthenticationStatus.Authenticated:
                NotLoggedIn.Visible = false;
                Session["GoogleIdentifier"] = response.ClaimedIdentifier.ToString();

                var fetchResponse = response.GetExtension<FetchResponse>();
                Session["FetchResponse"] = fetchResponse;
                var response2 = Session["FetchResponse"] as FetchResponse;

                string UserName = response2.GetAttributeValue(WellKnownAttributes.Name.First) ?? "Guest"; // with the OpenID Claimed Identifier as their username.
                string UserEmail = response2.GetAttributeValue(WellKnownAttributes.Contact.Email) ?? "Guest";

                Session["username"] = UserName;
                Session["useremail"] = UserEmail;

                Response.Redirect("Default2.aspx");
                break;

            case AuthenticationStatus.Canceled:
                lblAlertMsg.Text = "Cancelled.";
                break;

            case AuthenticationStatus.Failed:
                lblAlertMsg.Text = "Login Failed.";
                break;
        }

    }
    var CommandArgument = "https://www.google.com/accounts/o8/id";
    string discoveryUri = CommandArgument.ToString();
    OpenIdRelyingParty openid = new OpenIdRelyingParty();

    var url = new UriBuilder(Request.Url) { Query = "" };
    var request = openid.CreateRequest(discoveryUri); // This is where you would add any OpenID extensions you wanted
    var fetchRequest = new FetchRequest(); // to fetch additional data fields from the OpenID Provider

    fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
    fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.First);
    fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last);
    fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.HomeAddress.Country);
    request.AddExtension(fetchRequest);

    request.RedirectToProvider();
   }
 }

6 Comments

This looks like it's retrieving the user's contacts? I only want the e-mail address of the authorized user
The user logged in via OAuth
did you use admin account of Google??
To clarify. I am asking the end user to authorize my application via OAuth2 request. I would like the e-mail address of this user.
|
-1

Complete code to get UserProfile data.

var secrect = new ClientSecrets()
{
    ClientId = "myClientId",
    ClientSecret = "mySecret"
};

var scopes = new[] { Oauth2Service.Scope.UserinfoEmail, auth2Service.Scope.UserinfoProfile };

UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(secrect, scopes, "user", CancellationToken.None).Result;
    
var oauthSerivce = new Oauth2Service(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "MyApplicationName",
});

var userInfo = oauthSerivce.Userinfo.Get().Execute();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.