【问题标题】:How to get Profile Info from the Google API in c#如何从 C# 中的 Google API 获取配置文件信息
【发布时间】:2019-08-16 15:37:49
【问题描述】:

我正在使用 c# 在 vs2017 中构建一个 Web 应用程序。我的要求是允许用户通过谷歌登录进行登录。 请注意,我不知道 MVC,所以我必须在 .cs 页面中编写代码

我已经阅读了这篇文章https://developers.google.com/identity/sign-in/web/sign-in并相应地实现了它。

我还创建了 oAuth 客户端 ID 和客户端密码。

我也安装了 - Install-Package Google.Apis.Oauth2.v2 -Version 1.38.0.1532

对于如何进一步进行,我完全空白。看了这么多文章,不知道怎么用c#代码实现。

如何将访问令牌发送到 API - 有这么多 API - 这将获取所有这些信息,即名字、姓氏、出生日期或年龄、电话号码、电子邮件、地址、城市或城镇, 邮政编码?

我了解 People API 会获取我的电子邮件和全名。

如果有人可以帮助我继续前进,我将不胜感激,因为我应该安装更多的 nuget 包以及如何通过 c# 代码将令牌发送到 API

  1. 在 Test.aspx 页面中创建了一个按钮

    function onSignIn(googleUser) {
        var profile = googleUser.getBasicProfile();
        console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
         // The ID token you need to pass to your backend:
    
        var id_token = googleUser.getAuthResponse().id_token;
        console.log("ID Token: " + id_token);
    
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
    
    
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://localhost:53028/1.aspx');
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function () {
            console.log('Signed in as: ' + xhr.responseText);
        };
        xhr.send('idtoken=' + id_token);
    }
    

在 1.aspx.cs 上

string idToken = Request.Form["idtoken"].Trim();

我想要名字、姓氏、出生日期或年龄、电话号码、电子邮件、地址、城市或城镇、邮政编码。

更新:我在我的 .cs 文件中添加了这些代码行,它返回了名称。

    UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
           new ClientSecrets
           {
               ClientId = "1basa5.apps.googleusercontent.com",
               ClientSecret = "AG0LvAwZAD123"
           },
           new[] { "profile", "https://www.googleapis.com/auth/contacts.readonly" },
           "me",
           CancellationToken.None).Result;

        // Create the service.
        var service = new PeopleService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "M_Test",
        });

        PeopleResource.GetRequest peopleRequest = service.People.Get("people/me");
        peopleRequest.RequestMaskIncludeField = "person.names";
        Person profile = peopleRequest.Execute();

那么 id_Token 在这里有什么用呢?我是否应该不通过它 xhr.send('idtoken=' + id_token);从客户端页面?

【问题讨论】:

  • 请您用您的更新打开一个新问题,而不是添加到原始问题,此更新与原始问题无关。这是一个全新的问题。那我很乐意回答。
  • @Happy Singh 请告诉我,您最终采用了哪种方法来完成它!

标签: c# google-oauth google-signin google-api-dotnet-client


【解决方案1】:

您可以调用人员 api 并请求信息,只需设置授权标头并添加访问令牌。

GET /v1/people/me HTTP/1.1
Host: people.googleapis.com
Content-length: 0
Authorization: Bearer [Access Token]

您实际上并未使用 .net 客户端库。您可能想尝试关注Web authorization

请注意,此信息只有在用户填写后才可用。还有一些其他限制。

  • 名字,姓氏(只返回名字)
  • 出生日期或年龄(仅在设置为公开时返回)
  • 电话号码(仅在设置为公开时返回)
  • 电子邮件(仅返回电子邮件范围)

【讨论】:

  • 感谢 DaImTo,我的问题是我在 .cs 文件中获取了 idtoken,现在我应该如何调用我的 people api 并传递此令牌并获取所需的信息?
  • 您不能使用 id 令牌来调用 API 访问令牌。您需要使用访问令牌。您可以将 id 令牌解密为 jwt id 令牌,其中有一些用户声明,但不是您要查找的所有内容。
  • 那么在 .cs 文件中获取所需信息的最佳解决方案是什么?
  • 按照我链接的教程而不是自己编写代码将是 IMO 的最佳解决方案。
【解决方案2】:

我正在使用这个documentation 1.首先你需要获取代码。您必须像这样为用户生成 url:

                    var serv = app.Request.Url.GetLeftPart(UriPartial.Authority);
                    var str = "https://accounts.google.com/o/oauth2/v2/auth" +
                        "?scope=" + HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email") +
                        "&response_type=" + "code" + 
                        "&access_type=offline" + 
                        "&client_id=" + clien_id +
                        "&state=" + "test" +
                        "&redirect_uri=" + HttpUtility.UrlEncode(serv + "/index.html?action=google");

                    app.Response.Redirect(str);
  1. 在 action=google 中,您可以使用此功能在令牌上交换代码。

    static bool GetAccessToken(string access_code, string redirect_url, out string token)
    {
        try
        {
            var clien_id = ConfigurationManager.AppSettings["google_app_id"];
            var clien_secret = ConfigurationManager.AppSettings["google_app_secret"];
    
            var webRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/oauth2/v4/token");
    
            webRequest.Method = "POST";
    
            string parameters = $"code={access_code}&client_id={clien_id}&client_secret={clien_secret}&redirect_uri={redirect_url}&grant_type=authorization_code";
    
            var byteArray = Encoding.UTF8.GetBytes(parameters);
    
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = byteArray.Length;
    
            var postStream = webRequest.GetRequestStream();
    
            // Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();
    
            var response = webRequest.GetResponse();
            postStream = response.GetResponseStream();
    
            var reader = new StreamReader(postStream);
            var tmp = reader.ReadToEnd();
    
            var pat = "\"access_token\"";
            var ind = tmp.IndexOf(pat); 
    
            if (ind != -1)
            {
                ind += pat.Length;
    
                ind = tmp.IndexOf("\"", ind);
    
                if (ind != -1)
                {
                    var end = tmp.IndexOf("\"", ind + 1);
    
                    if (end != -1)
                    {
                        token = tmp.Substring(ind + 1, end - ind - 1);
    
                        return true;
                    }
                }
            }
    
            token = tmp;
        }
        catch (Exception e)
        {
            Debug.WriteLine(e);
    
            token = e.Message;
        }
    
        return false;
    }
    
  2. 获取用户资料

        var access_code = app.Request.QueryString["code"];
    
        if (access_code == null)
        {
            return;
        }
    
        var serv = app.Request.Url.GetLeftPart(UriPartial.Authority);
        var access_token = "";
    
        if (!GetAccessToken(access_code, HttpUtility.UrlEncode(serv + "/index.html?action=google"), out access_token))
        {
            return;
        }
    
        var res = "";
        var web = new WebClient();
    
        web.Encoding = System.Text.Encoding.UTF8;
    
        try
        {
            res = web.DownloadString("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + access_token);
        }
        catch (Exception ex)
        {
            return;
        }
    

【讨论】:

    猜你喜欢
    • 2019-08-22
    • 1970-01-01
    • 2013-07-24
    • 2017-09-06
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多