Search code examples
c#google-authenticationgoogle-oauthgoogle-openid

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

I don't know from where i can store the user information in my table, actually I don't know about google authentication and i find ths=is code on stackoverflow

I just want to store all the information in a table and if a user is logged in for the first time the page should be redirected to new user page and if the user is old user the page should redirect to welcome page


Solution

  • To start with, I definitely agree that Google's documentation is a murky business.

    There are a couple of different ways in which you can validate the integrity of the ID token on the server side (btw this is the page you're looking for):

    1. "Manually" - constantly download Google's public keys, verify signature and then each and every field, including the iss one; the main advantage (albeit a small one in my opinion) I see here is that you can minimize the number of requests sent to Google).
    2. "Automatically" - do a GET on Google's endpoint to verify this token https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}
    3. Using a Google API Client Library - like the official one.

    Here's how this could look:

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