使用Google API for .NET访问用户信息

我正在使用Google API Preview(1.7.0)通过OAuth2授权用户。 我一直在关注示例MVC代码 。 这是我对FlowMetadata实现:

 private static readonly IAuthorizationCodeFlow flow = ...; // Implementation of tokens public static async Task 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? } } 

我现在有一个有效的UserCredential ,因此有访问令牌,但我找不到任何托管API来访问用户信息。 我确实找到了这个问题 ,但这似乎假设我只是提出原始请求,而不是使用官方库。

如何获取用户的电子邮件地址?

您应该执行以下操作:

  1. 除了Google.Apis.Auth NuGet包之外,您还应安装以下页面: https ://www.nuget.org/packages/Google.Apis.Oauth2.v2

  2. Google.Apis.Oauth2.v2.Oauth2Service.Scope.UserinfoProfile以及Google.Apis.Oauth2.v2.Oauth2Service.Scope.UserinfoEmail添加到范围列表中(初始化AppFlowMetadata时)。

  3. 现在,添加以下代码:

 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, ... } 

在这里,我编辑我的回答。 请看看这个。 在Default2.aspx页面上,我在标签中显示Session [“username”]和Session [“useremail”]值。 我希望这些对你有所帮助。

 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(); 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(); } } 

将范围设置为:

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

并使用此端点地址: https : //www.googleapis.com/oauth2/v1/userinfo ?alt = json

这应该可以帮助您获取所需的信息。