在Google身份验证中将用户信息输入数据库

时间:2016-07-28 09:18:59

标签: c# google-oauth google-authentication google-oauth2 google-openid

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

我不知道从哪里可以将用户信息存储在我的表中, 实际上我不知道google身份验证,我发现ths =是stackoverflow上的代码

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

1 个答案:

答案 0 :(得分:1)

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

您可以通过几种不同的方式验证服务器端ID令牌的完整性(btw this是您正在寻找的页面):

  1. &#34;手动&#34; - 不断下载Google的公钥,验证签名,然后检查每个字段,包括iss个字段;主要优势(虽然我认为是一个小优势)我在这里看到的是,您可以最大限度地减少发送给Google的请求数量。
  2. &#34;自动&#34; - 在Google的终端上进行GET以验证此令牌 https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}
  3. 使用Google API客户端库 - 例如official one
  4. 以下是这样的看法:

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