【问题标题】:.NET OAuth Google API.NET OAuth 谷歌 API
【发布时间】:2014-02-03 19:35:11
【问题描述】:

我正在尝试实现 OAuth Google API,但没有找到任何开始的 elegnat 示例。不知何故,我与http://dotnetopenauth.net/ 相提并论

我创建了一个名为“Login.aspx”的页面,其中包含代码

using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
using DotNetOpenAuth.OpenId.RelyingParty;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GoogleOAuth
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
             var openid = new OpenIdRelyingParty();
            var response = openid.GetResponse();
            //Checks whether user is authenticated or not
            if (response != null && response.Status == AuthenticationStatus.Authenticated && response.Provider.Uri == new Uri("https://www.google.com/accounts/o8/ud"))
            {
                var fetch = response.GetExtension<FetchResponse>();
                string email = String.Empty;
                if (fetch != null)
                {
                    email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email); //Fetching requested emailid
                }

            }
        }
        protected void GoogleButtonClick(object sender, EventArgs e)
        {
            using (var openid = new OpenIdRelyingParty())
            {
                var request = openid.CreateRequest("https://www.google.com/accounts/o8/id");
                var fetch = new FetchRequest();
                fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email); // Request for email id
                request.AddExtension(fetch); // Adding in request obj
                request.RedirectToProvider();
            }
        }
    }
}

在此页面上,它工作正常。启动上述代码后,返回电子邮件地址。但是我想知道在用户登录后转移用户并在不同页面上而不是在同一页面上获取数据。怎么可能?

如果我复制了 Page_Load 中的代码,然后粘贴到其他页面,它就不起作用了。返回 null 作为响应。

请推荐

【问题讨论】:

    标签: c# .net oauth google-oauth


    【解决方案1】:

    我建议您首先使用 C# 和 Google.Apis.v3。根据您尝试访问的 API 会略有不同。

    UserCredential credential; 
    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
              new ClientSecrets { ClientId = "YourClientId", ClientSecret = "YourClientSecret" },
              new[] { DriveService.Scope.Drive,
                DriveService.Scope.DriveFile },
              "user",
              CancellationToken.None,
              new FileDataStore("Drive.Auth.Store")).Result; }
    

    这是一个将连接到 Google Drive 的 Oauth 示例。从您尝试访问 google+ 的代码的外观来看,范围会有所不同。

    您可以在此处找到开始使用 Google Oath2 的基本教程:Google OAuth2 C#

    【讨论】:

    • 谢谢!在 Google 的文档中找不到任何示例,我快疯了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 2021-08-11
    • 2021-10-02
    • 1970-01-01
    相关资源
    最近更新 更多