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

时间:2014-01-23 14:00:47

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

我正在使用Google API Preview(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,但这似乎假设我只是在做原始请求,而不是使用官方库。

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

4 个答案:

答案 0 :(得分:20)

您应该执行以下操作:

  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. 现在,添加以下代码:

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

答案 1 :(得分:2)

将您的范围设置为:

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

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

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

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

获取用户配置文件数据的完整代码。

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