【发布时间】: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
-
在 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