在 google 认证中获取用户信息到数据库

get user information into database in google authentication

    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; }
}

我不知道从哪里可以将用户信息存储在 table 中, 实际上我不知道 google 身份验证,我在 Whosebug

上找到了 ths=is 代码

我只想将所有信息存储在 table 中,如果用户是第一次登录,页面应该重定向到新用户页面,如果用户是老用户,页面应该重定向到欢迎页面

首先,我绝对同意 Google 的文档是一个模糊的业务。

您可以通过多种不同的方式在服务器端验证 ID 令牌的完整性(顺便说一下,this 是您要查找的页面):

  1. "Manually" - 不断下载 Google 的 public 密钥,验证签名,然后验证每个字段,包括 iss 一个;我在这里看到的主要优势(尽管在我看来很小)是您可以最大限度地减少发送到 Google) 的请求数量。
  2. "Automatically" - 在 Google 的端点上执行 GET 以验证此令牌 https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}
  3. 使用 Google API 客户端库 - 如 official one.

这是它的样子:

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
    };
}