2014-01-23 94 views
6

我正在使用Google API预览版(1.7.0)通过OAuth2授权用户。我一直在关注sample MVC code。这是我实现FlowMetadata使用Google API for .NET访问用户信息

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,但这似乎认为我只是提出原始请求,而不是使用官方库。

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

+0

你可以张贴的'私人静态只读IAuthorizationCodeFlow流码= ...; //执行令牌。其实我被困在那一点,并没有得到任何解决方案。这里是[链接](https://stackoverflow.com/questions/44842813/google-calendar-api-working-fine-locally-but-not-raising-its-authentication-on-s)到我的问题 – Divya

+0

现在我会遇到这个问题。 [我的问题](https://stackoverflow.com/questions/45103628/access-to-the-path-c-windows-system32-config-systemprofile-is-denied) – Divya

回答

18

你应该做到以下几点:

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

伟大的工作。我对你的回答只做了一些小调整,就是添加'Google.Apis.Oauth2.v2.Oauth2Service.Scope.UserinfoEmail'范围:) – CodingIntrigue

+1

凭证呢? –

+0

@SebastiánRojasresult.Credential – razon

0

在这里,我编辑我的答案。请看看这个。在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(); 
    } 
} 
+0

这看起来像是检索用户的联系人?我只想要授权用户的电子邮件地址 – CodingIntrigue

+0

授权用户? –

+0

用户通过OAuth登录 – CodingIntrigue

相关问题