我正在使用C#在vs2017中构建Web应用程序。我的要求是允许用户通过Google登录名进行登录。 请注意,我不知道MVC,所以我必须在.cs页中编写代码
我已阅读本文https://developers.google.com/identity/sign-in/web/sign-in,并相应地执行了该文章。
我还创建了oAuth客户端ID和客户端密码。
我还安装了-Install-Package Google.Apis.Oauth2.v2-版本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);在客户页面上?
答案 0 :(得分:0)
您可以调用people api并请求信息,只需设置授权标头并添加访问令牌即可。
GET /v1/people/me HTTP/1.1
Host: people.googleapis.com
Content-length: 0
Authorization: Bearer [Access Token]
您实际上并未使用.net客户端库。您可能要尝试关注Web authorization
请注意,只有在用户填写此信息后,该信息才可用。还有其他一些限制。
答案 1 :(得分:0)
我使用此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);
在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;
}
获取用户个人资料
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;
}