Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access User Info using Google APIs for .NET

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?

like image 854
CodingIntrigue Avatar asked Jan 23 '14 14:01

CodingIntrigue


People also ask

Is it safe to expose Google client ID?

Web application secrets If the client secret is of the web type, then yes: you should absolutely not post it, and invalidate it if it gets exposed. This would allow a malicious entity to impersonate your backend and perform actions on your users' accounts on your behalf.


3 Answers

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, ... 
}
like image 155
peleyal Avatar answered Oct 15 '22 14:10

peleyal


Set your scopes to:

  • https://www.googleapis.com/auth/userinfo.email
  • https://www.googleapis.com/auth/userinfo.profile

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.

like image 21
Yair Nevet Avatar answered Oct 15 '22 15:10

Yair Nevet


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();
   }
 }
like image 28
Anurag Jain Avatar answered Oct 15 '22 14:10

Anurag Jain