我正在使用c#在vs 2017中构建一个Web应用程序。我的要求是允许用户通过Google登录进行登录。请注意我不知道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
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);从客户端页面?
您可以调用people api并请求设置授权标头的信息并添加访问令牌。
GET /v1/people/me HTTP/1.1
Host: people.googleapis.com
Content-length: 0
Authorization: Bearer [Access Token]
您实际上没有使用.net客户端库。您可能想尝试以下Web authorization
请注意,只有当用户填写此信息时,此信息才可用。还有一些其他限制。
我使用这个documentation 1.首先你需要获取代码。您必须为此用户生成网址:
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);
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;
}
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;
}