News
IBM to offer mobile security as a service IBM will start delivering mobile security-as-a-service (MaaS) through its own cloud infrastructure in India, a move that is expected to better address in-country data requirements... IBM Spectrum Computing: IBM has enlarged its portfolio of software-defined infrastructure solutions with cognitive features for workload management.  * LiFi internet technology has been introduced, the new type of wireless internet connection that gives 100 times faster than traditional WiFi -- Invented by Professor Harald Haas from the University of Edinburgh. * Sci. Rachid Yazami has developed a smart chip that charges smartphones in less than 10 minutes. BenQ has launched BlueCore projector - Consumer electronics major BenQ has launched its first BlueCore laser light source projector. For those unaware, devices with BlueCore laser technology have a high contrast output of 80000:1 with an extended lamp life and efficiency. *** 
  Apr 3 2016 1:04PM     Anand
  1 Comments    10781 Views  
In this article Anand demonstrates, how to authenticate the User Using google account in C#.
Service accounts
1. Go to the Google Developer Console

2. Select a project, or create a new one.

3. Name the project "MyFirstProject" and click on Create button.
4. Once you created your project succesfully, In the sidebar on the left, select Content Screen and Fill the mandatory information about your product.

5. Click on Save Button.

5. In the sidebar on the left, select Credentials.

6. To set up a new web Application, do the following: Under the OAuth heading, select Create new Client ID.

7. When prompted, select Web application, your authorized URI should be "http://localhost:2812/LoginWithGoogleAcc.aspx".

8. Click Create Client ID.
Now you can find Client Id, Email Address, Client Secret , Redirect URIs and JavaScript Origins like below image.
Now Open VS and Create Empty web application.
Add a new Item "Default.aspx" and paste the below code with your account credentials.
Default.aspx
<head runat="server">
    <title></title>
    <style type="text/css">
        .btnLogInGoogle
        {
            cursor: pointer;
            height: 39px;
            background-color: #81B441 !important;
            color: #FFF;
            font-weight: 700;
            border: none;
            border-radius: 10px;
        }

    
</style> 
    <script type="text/javascript" language="javascript">
        function OpenGoogleLoginPopup() {
            var url = "https://accounts.google.com/o/oauth2/auth?";
            url += "scope=https://www.googleapis.com/auth/userinfo.profile
 https://www.googleapis.com/auth/userinfo.email&"
;
            url += "state=%2Fprofile&"
            url += "redirect_uri=http://localhost:2812/LoginWithGoogleAcc.aspx&"
            url += "response_type=token&"
            url += "client_id= xxxxx paste your clientId Here xxxxxxx";
            window.location = url;
        }
    </script> 
</head>
<body>
    <input class="btnLogInGoogle w150px" type="button" id="Button1"
                            runat="server" value="Login With Google" onclick="OpenGoogleLoginPopup();" />

</body>
Add a another new Item "LoginWithGoogleAcc.aspx" which is given "Redirect URIs" in Developers Console and paste the below code.
LoginWithGoogleAcc.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script type="text/javascript" language="javascript">
        try {
            // First, parse the query string
            var params = {}, queryString = location.hash.substring(1),
    regex = /([^&=]+)=([^&]*)/g, m;
            while (m = regex.exec(queryString)) {
                params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
            }
            var ss = queryString.split("&")
            // window.location = "Home.aspx?" + ss[1];
            if (ss != undefined) {
                window.location = "Home.aspx?" + ss[1];
                history.pushState("""""Home.aspx");
            }
            else
                window.location = "Home.aspx";


        } catch (exp) {

        }
    </script> 
</head>
<body>
</body>
</html>
Add a another new Item "Home.aspx" to get response about clients.
Home.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <div id="ClientDetails">
    <br ><br >
    <asp:Label ID="ClientName" runat="server" ></asp:Label><br >

    <asp:Label ID="ClientEmail" runat="server"></asp:Label><br >

    <asp:Image id="imgProfile" runat="server" Width="16%" /><br >
    
    
    </div>
</body>
</html>
Home.aspx.cs
public partial class Home : System.Web.UI.Page
    {
        public string Email_address = "";
        public string Google_ID = "";
        public string firstName = "";
        public string LastName = "";
        public string Client_ID = "";
        public string Return_url = "";
        public string userProfilePic = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["access_token"] != null)
            {
                string test = Request.QueryString["access_token"];
            }
            if (Request.QueryString["access_token"] != null)
            {

                String URI = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + 
Request.QueryString["access_token"].ToString();

                WebClient webClient = new WebClient();
                Stream stream = webClient.OpenRead(URI);
                string b;

                /*I have not used any JSON parser because I do not want to use any extra dll/3rd party dll*/
                using (StreamReader br = new StreamReader(stream))
                {
                    b = br.ReadToEnd();
                }

                b = b.Replace("id""").Replace("email""");
                b = b.Replace("given_name""");
                b = b.Replace("family_name""").Replace("link""").Replace("picture""");
                b = b.Replace("gender""").Replace("locale""").Replace(":""");
                b = b.Replace("\"""").Replace("name""").Replace("{""").Replace("}""");

                /*
                 
                "id": "109124950535374******"
                  "email": "usernamil@gmail.com"
                  "verified_email": true
                  "name": "firstname lastname"
                  "given_name": "firstname"
                  "family_name": "lastname"
                  "link": "https://plus.google.com/10912495053537********"
                  "picture": "https://lh3.googleusercontent.com/......./photo.jpg"
                  "gender": "male"
                  "locale": "en" } 
               */


                Array ar = b.Split(",".ToCharArray());
                for (int p = 0; p < ar.Length; p++)
                {
                    ar.SetValue(ar.GetValue(p).ToString().Trim(), p);

                }
                Email_address = ar.GetValue(1).ToString();
                Google_ID = ar.GetValue(0).ToString();
                firstName = ar.GetValue(4).ToString();
                LastName = ar.GetValue(5).ToString();
                userProfilePic = ar.GetValue(7).ToString();
                userProfilePic = userProfilePic.Replace("https""https:");
                
                imgProfile.ImageUrl = userProfilePic;
                ClientEmail.Text = Email_address;
                ClientName.Text = firstName + " " + LastName;
                
            }
        }
    }
For Demo, you can try login with Google Account in this Website.
I hope this page will helps you to validate user using Google Account in C# .Thanks.
BackToTop
Comments


AnonymousUser
Jun 28 2018 12:54AM
Hi Anand, can you do article/tutorial on how to implementing WCF service for google (without using browser) like this link. By using this link (http://qaru.site/questions/1274790/wpf-application-authentication-with-google), i have try to move and implement the function and try make it as a WCF service interface. This is difficult for me to do it and become problematic. Can you teach the same thing the project done in wcf service.

 
Search
Recent Posts
Create Amazon ElasticCache Using Memcached in CSharp
Oct 29 2018 12:09PM Posted By Amose
Get Google Map Lat Lng (Geo Point) By Pincode in C#
Oct 28 2018 12:09PM Posted By Pranav
Google URL Shortener in C#
Oct 20 2018 12:09PM Posted By Sanjay
Bind Gridview from CSV file in Asp.Net C#
Oct 5 2018 12:09PM Posted By Michael
Call WebService method from jQuery in every 1 minute
Sep 26 2018 12:09PM Posted By John
Gridview custom CSS in ASP.Net
Sep 14 2018 12:09PM Posted By Micheal Ryan
Read excel file and bind to Gridview in C#
Sep 10 2018 12:09PM Posted By Micheal
Tags
Follow us on Facebook
Follow us on Google +
Recent post in your Email inbox.
Enter your email address: