C# 在google身份验证中将用户信息输入数据库 使用系统; 使用System.Collections.Generic; 使用System.Linq; 使用System.Web; 使用System.Web.UI; 使用System.Web.UI.WebCont
在google身份验证中将用户信息输入数据库C# 在google身份验证中将用户信息输入数据库 使用系统; 使用System.Collections.Generic; 使用System.Linq; 使用System.Web; 使用System.Web.UI; 使用System.Web.UI.WebCont,c#,google-authentication,google-oauth,google-openid,C#,Google Authentication,Google Oauth,Google Openid,在google身份验证中将用户信息输入数据库 使用系统; 使用System.Collections.Generic; 使用System.Linq; 使用System.Web; 使用System.Web.UI; 使用System.Web.UI.WebControl; 利用制度全球化; Net系统; 使用System.Security.Cryptography; 使用系统文本; 使用System.IO; 使用Newtonsoft.Json; 使用System.Net.Http; 公共部分类\u默认值
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Web;
使用System.Web.UI;
使用System.Web.UI.WebControl;
利用制度全球化;
Net系统;
使用System.Security.Cryptography;
使用系统文本;
使用System.IO;
使用Newtonsoft.Json;
使用System.Net.Http;
公共部分类\u默认值:System.Web.UI.Page
{
受保护的字符串googleplus\u client\u id=“clientid”;
受保护的字符串googleplus\u client\u sceret=“id”;
受保护的字符串googleplus\u重定向\u url=”http://localhost“;//将其替换为重定向URL;开发者的重定向URL。google应用程序应与此URL匹配。
受保护的字符串参数;
受保护的无效页面加载(对象发送方、事件参数e)
{
如果(Session.Contents.Count>0)
{
如果(会话[“loginWith”]!=null)
{
如果(会话[“loginWith”].ToString()=“google”)
{
尝试
{
var url=Request.url.Query;
如果(url!=“”)
{
字符串queryString=url.ToString();
char[]delimiterChars={'='};
string[]words=queryString.Split(delimiterChars);
字符串代码=单词[1];
如果(代码!=null)
{
//获取访问令牌
HttpWebRequest webRequest=(HttpWebRequest)webRequest.Create(“https://accounts.google.com/o/oauth2/token");
webRequest.Method=“POST”;
Parameters=“code=“+code+”&client\u id=“+googleplus\u client\u id+”&client\u secret=“+googleplus\u client\u sceret+”&redirect\u uri=“+googleplus\u redirect\u url+”&grant\u type=authorization\u code”;
byte[]byteArray=Encoding.UTF8.GetBytes(参数);
webRequest.ContentType=“application/x-www-form-urlencoded”;
webRequest.ContentLength=byteArray.Length;
Stream postStream=webRequest.GetRequestStream();
//将post数据添加到web请求
Write(byteArray,0,byteArray.Length);
postStream.Close();
WebResponse=webRequest.GetResponse();
postStream=response.GetResponseStream();
StreamReader=新的StreamReader(postStream);
字符串responseFromServer=reader.ReadToEnd();
GooglePlusAccessToken serStatus=JsonConvert.DeserializeObject(responseFromServer);
if(serStatus!=null)
{
string accessToken=string.Empty;
accessToken=serStatus.access\u令牌;
如果(!string.IsNullOrEmpty(accessToken))
{
//getgoogleplususerdataSer(accessToken);
}
其他的
{ }
}
其他的
{ }
}
其他的
{ }
}
}
捕获(例外情况除外)
{
//抛出新异常(例如Message、ex);
重定向(“index.aspx”);
}
}
}
}
}
受保护的无效按钮1\u单击(对象发送者,事件参数e)
{
var Googleurl=”https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=“+googleplus\u重定向\u url+”&范围=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&client_id=“+googleplus_客户id;
会话[“loginWith”]=“google”;
重定向(Googleurl);
}
公共类GooglePlusAccessToken
{
公共字符串访问\u令牌{get;set;}
公共字符串标记\u类型{get;set;}
{get;set;}中的公共int过期
公共字符串id_标记{get;set;}
公共字符串刷新\u标记{get;set;}
}
私有异步void getgoogleplususerdataSer(字符串访问\u令牌)
{
尝试
{
HttpClient=新的HttpClient();
var urlProfile=”https://www.googleapis.com/oauth2/v1/userinfo?access_token=“+接入令牌;
client.CancelPendingRequests();
HttpResponseMessage输出=wait client.GetAsync(urlProfile);
if(输出.IsSuccessStatusCode)
{
string outputData=await output.Content.ReadAsStringAsync();
GoogleUserOutputData serStatus=JsonConvert.DeserializeObject(outputData);
if(serStatus!=null)
{
//您将在此处获得用户信息。
}
}
}
捕获(例外情况除外)
{
//捕捉异常
}
}
}
公共类GoogleUserOutputData
{
公共字符串id{get;set;}
公共字符串名称{get;set;}
给定名称的公共字符串{get;set;}
公共字符串电子邮件{get;set;}
公共字符串图片{get;set;}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using System.Net.Http;
public partial class _Default : System.Web.UI.Page
{
protected string googleplus_client_id = "clientid";
protected string googleplus_client_sceret = "id";
protected string googleplus_redirect_url="http://localhost"; // Replace this with your Redirect URL; Your Redirect URL from your developer.google application should match this URL.
protected string Parameters;
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Contents.Count > 0)
{
if (Session["loginWith"] != null)
{
if (Session["loginWith"].ToString() == "google")
{
try
{
var url = Request.Url.Query;
if (url != "")
{
string queryString = url.ToString();
char[] delimiterChars = { '=' };
string[] words = queryString.Split(delimiterChars);
string code = words[1];
if (code != null)
{
//get the access token
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
webRequest.Method = "POST";
Parameters = "code=" + code + "&client_id=" + googleplus_client_id + "&client_secret=" + googleplus_client_sceret + "&redirect_uri=" + googleplus_redirect_url + "&grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes(Parameters);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
Stream postStream = webRequest.GetRequestStream();
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
WebResponse response = webRequest.GetResponse();
postStream = response.GetResponseStream();
StreamReader reader = new StreamReader(postStream);
string responseFromServer = reader.ReadToEnd();
GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);
if (serStatus != null)
{
string accessToken = string.Empty;
accessToken = serStatus.access_token;
if (!string.IsNullOrEmpty(accessToken))
{
// getgoogleplususerdataSer(accessToken);
}
else
{ }
}
else
{ }
}
else
{ }
}
}
catch (Exception ex)
{
//throw new Exception(ex.Message, ex);
Response.Redirect("index.aspx");
}
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
var Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" + googleplus_redirect_url + "&scope=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&client_id=" + googleplus_client_id;
Session["loginWith"] = "google";
Response.Redirect(Googleurl);
}
public class GooglePlusAccessToken
{
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in { get; set; }
public string id_token { get; set; }
public string refresh_token { get; set; }
}
private async void getgoogleplususerdataSer(string access_token)
{
try
{
HttpClient client = new HttpClient();
var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + access_token;
client.CancelPendingRequests();
HttpResponseMessage output = await client.GetAsync(urlProfile);
if (output.IsSuccessStatusCode)
{
string outputData = await output.Content.ReadAsStringAsync();
GoogleUserOutputData serStatus = JsonConvert.DeserializeObject<GoogleUserOutputData>(outputData);
if (serStatus != null)
{
// You will get the user information here.
}
}
}
catch (Exception ex)
{
//catching the exception
}
}
}
public class GoogleUserOutputData
{
public string id { get; set; }
public string name { get; set; }
public string given_name { get; set; }
public string email { get; set; }
public string picture { get; set; }
}
private const string GoogleApiTokenInfoUrl = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}";
public ProviderUserDetails GetUserDetails(string providerToken)
{
var httpClient = new MonitoredHttpClient();
var requestUri = new Uri(string.Format(GoogleApiTokenInfoUrl, providerToken));
HttpResponseMessage httpResponseMessage;
try
{
httpResponseMessage = httpClient.GetAsync(requestUri).Result;
}
catch (Exception ex)
{
return null;
}
if (httpResponseMessage.StatusCode != HttpStatusCode.OK)
{
return null;
}
var response = httpResponseMessage.Content.ReadAsStringAsync().Result;
var googleApiTokenInfo = JsonConvert.DeserializeObject<GoogleApiTokenInfo>(response);
if (!SupportedClientsIds.Contains(googleApiTokenInfo.aud))
{
Log.WarnFormat("Google API Token Info aud field ({0}) not containing the required client id", googleApiTokenInfo.aud);
return null;
}
return new ProviderUserDetails
{
Email = googleApiTokenInfo.email,
FirstName = googleApiTokenInfo.given_name,
LastName = googleApiTokenInfo.family_name,
Locale = googleApiTokenInfo.locale,
Name = googleApiTokenInfo.name,
ProviderUserId = googleApiTokenInfo.sub
};
}