【问题标题】:Access User Info using Google APIs for .NET使用适用于 .NET 的 Google API 访问用户信息
【发布时间】:2014-02-14 03:02:54
【问题描述】:

我正在使用 Google API 预览版 (1.7.0) 通过 OAuth2 授权用户。我一直在关注sample MVC code。这是我对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?
    }
}

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

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

【问题讨论】:

  • 你能发private static readonly IAuthorizationCodeFlow flow = ...; // Implementation of tokens的代码吗?实际上我被困在那个点上并且没有得到任何解决方案。这是link我的问题
  • 现在我遇到了这个问题。 My Question

标签: c# .net asp.net-mvc google-api-dotnet-client


【解决方案1】:

您应该执行以下操作:

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

  2. Google.Apis.Oauth2.v2.Oauth2Service.Scope.UserinfoProfileGoogle.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, ... 
}

【讨论】:

  • 伟大的工作。我对您的回答所做的唯一细微调整是添加Google.Apis.Oauth2.v2.Oauth2Service.Scope.UserinfoEmail 范围:)
  • 凭证呢?
  • @SebastiánRojas result.Credential
  • 什么是结果?请不要只是复制/粘贴。如果有人也能解释一下会很有帮助
【解决方案2】:

将范围设置为:

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

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

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

【讨论】:

    【解决方案3】:

    在这里,我编辑我的答案。请调查一下。在 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<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();
       }
     }
    

    【讨论】:

    • 这看起来像是在检索用户的联系人?我只想要授权用户的电子邮件地址
    • 用户通过 OAuth 登录
    • 你用的是谷歌的管理员帐号吗??
    • 澄清一下。我要求最终用户通过OAuth2 request 授权我的应用程序。我想要这个用户的电子邮件地址。
    【解决方案4】:

    获取 UserProfile 数据的完整代码。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 2012-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多