Access User Info using Google APIs for .NET
Solution 1
You should do the following:
In addition to Google.Apis.Auth NuGet package you should install the following page: https://www.nuget.org/packages/Google.Apis.Oauth2.v2
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).
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, ... }
Solution 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.
Solution 3
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();
}
}
CodingIntrigue
I'm a C#/Javascript Software Developer with a particular interest in front-end frameworks such as Angular & jQuery and the Microsoft stack on the back-end. http://www.codingintrigue.co.uk @CodingIntrigue on Twitter
Updated on June 04, 2022Comments
-
CodingIntrigue almost 2 years
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?
-
CodingIntrigue about 10 yearsThis looks like it's retrieving the user's contacts? I only want the e-mail address of the authorized user
-
CodingIntrigue about 10 yearsThe user logged in via OAuth
-
Anurag Jain about 10 yearsdid you use admin account of Google??
-
CodingIntrigue about 10 yearsTo clarify. I am asking the end user to authorize my application via OAuth2 request. I would like the e-mail address of this user.
-
Anurag Jain about 10 years
-
Anurag Jain about 10 years@RGraham In this solution, User will be authenticated via OAuth then I fetch the email addrss. I hope , I am wright.
-
CodingIntrigue about 10 yearsGreat work. Only minor adjustment I made to your answer was to add the
Google.Apis.Oauth2.v2.Oauth2Service.Scope.UserinfoEmail
scope :) -
Sebastián Rojas over 7 yearsWhat about credential?
-
razon almost 7 years@SebastiánRojas result.Credential
-
Dan over 2 yearswhat is result? please dont just copy/paste. it will be helpful if someone can explain as well