Saturday 19 October 2013

How to get Gmail authentication in our ASP.NET web sites



Today am going to explain how to authenticate a person to enter our own web site using his Gmail credentials.

Purpose

Generally when a person registers himself in a website, a return mail is sent to him either confirming his registration or sending a password. If the user provides any invalid mail id also the application tries to send a mail. Even CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) code is also of no use when the user provides an invalid mail address. As majority of applications use SMTP (Simple Mail Transfer Protocol) no error message is displayed when Gmail returns a mailer demon message. This increases the processing time of the application and also wastes memory. Even sometimes we don’t want the user’s entire details to store in our database. In such conditions we’ll use Gmail authentication.
The Gmail authentication helps us to confirm that the registering person is a valid user. When we ask the user to register him using his Gmail credentials he need not worry about his password identification. When a person is registered using his Gmail credentials, the Gmail provides only the first and last name, date of birth, country, email id of the registered person. It won’t display the password, phone number, contacts of the registered person etc. even to the developer. So this is completely secured code .


In order to get the Gmail authentication we need to add a dll to the solution. The dll is
DotNetOpenAuth

You need to download this dll from internet. After downloading add this dll to the service references.
Once you add this dll your website will now have Gmail authentication.
Now we’ll look at the design code

<table>
<tr>
<td>
<div id="loginform">
<p>
                                                <div id="NotLoggedIn" runat="server">
                                                            Log in with Gmail to Comment. Press here -->&nbsp;
  <asp:Button ID="btnLoginToGoogle" Text="Sign In with Gmail" runat="server" OnCommand="OpenLogin_Click"
BackColor="#0391fb" CommandArgument="https://www.google.com/accounts/o8/id" Width="171px" />
                                                <p />
                                                <asp:Label runat="server" ID="lblAlertMsg" />
                                    </div>
</td>
</tr>
</table>

Now we’ll look at the code behind

First we need to declare a method and also should have the same method in the page load.

Let us declare a method called openIdAuth()

Now we’ll call this method in the page load

protected void Page_Load(object sender, EventArgs e)
{
            openIdAuth();
}

Now let’s see what will happen in the method openIdAuth()

protected void openIdAuth()
{
            OpenIdRelyingParty rp = new OpenIdRelyingParty();
            var response = rp.GetResponse();
            if (response != null)
            {
                switch (response.Status)
                {
                    case AuthenticationStatus.Authenticated:
                    //    NotLoggedIn.Visible = false;
                    var fetchResponse = response.GetExtension<FetchResponse>();
                    Session["FetchResponse"] = fetchResponse;
                    var response2 = Session["FetchResponse"] as FetchResponse;
                    // Use FormsAuthentication to tell ASP.NET that the user is now logged in,
                    // with the OpenID Claimed Identifier as their username.
                   string uname = response2.GetAttributeValue(WellKnownAttributes.Name.First) ?? "Guest";
     string mailID = response2.GetAttributeValue(WellKnownAttributes.Contact.Email) ?? "Guest";
                    Session["UserName"] = uname;
                    Session["EmailId"] = mailID;
     FormsAuthentication.RedirectFromLoginPage(uname,false);                                      Response.Redirect("~/Default.aspx"); //redirect to main page of your website
break;
               case AuthenticationStatus.Canceled:
               break;
               case AuthenticationStatus.Failed:
               lblAlertMsg.Text = "Login Failed.";
               break;
                }
     }
}

This method is called when the login button in the Gmail home page is clicked. Now we’ll look at the button click event code

protected void OpenLogin_Click(object src, CommandEventArgs e)
{
            string discoveryUri = e.CommandArgument.ToString();
            OpenIdRelyingParty openid = new OpenIdRelyingParty();
            var b = new UriBuilder(Request.Url) { Query = "" };
            var req = openid.CreateRequest(discoveryUri, b.Uri, b.Uri);
           var fetchRequest = new FetchRequest();
            fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
            fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.First);
            req.AddExtension(fetchRequest);
            req.RedirectToProvider();
}

1 comment:

  1. hi sir i am developing a site in c# and i need the code in which when i click on the button(connect with gmail) the request should go to the gmail account there i will fill my credentials and after authentication i must come back to my current webpage and i want to import all my gmail account contacts on the same page..plz give the code for that or give me your precious views

    ReplyDelete