Tuesday, 12 June 2012

How to Integrate Gmail Login into your ASP.Net Website

Google supports the OpenID 2.0 protocol, providing authentication support as an OpenID provider. On request from a third-party site, Google authenticates users who are signing in with an existing Google account, and returns to the third-party site an identifier that the site can use to recognize the user. This identifier is consistent, enabling the third-party site to recognize the user across multiple sessions.

Note: OpenID authentication now supports Google Apps (hosted) accounts. 

OpenID authentication process

OpenID login authentication for web applications involves a sequence of interactions between your web application, Google's login authentication service, and the end user.

 

Working with OpenID

1. The web application asks the end user to log in by offering a set of log-in options, including using their Google account.


2. Login by credentials.

 3. The web application sends a "discovery" request to Google to get information on the Google login authentication endpoint.

4. Google returns an XRDS document, which contains the endpoint address and then web application sends a login authentication request to the Google endpoint address.

5. Once logged in, Google displays a confirmation page and notifies the user that a third-party application is requesting authentication. Page ask for allow approval and don't approval.


6. If the user approves the authentication, Google returns the user details.

7. If you want to retrieve the user's details of currently logged in google user, then use OpenAuth/OpenID. For .Net, a library is available to do all this task, DotNetOpenAuth. Download it, extract it and add in your bin folder of application.

Source Code:


Add code in your login.aspx page:

<style type="text/css">
.btngoogle
{
    background-image:url(images/google+login+button.png);
    border:1px solid white;
    cursor:pointer;
    }
</style>
<script type="text/javascript">
    function showimage() {
        var i = document.getElementById("imggoogle");
        i.src = "images/google+logout+button.png";
        i.style.border = "1px solid white";
    }

</script>
<asp:Button ID="btnLoginToGoogle" runat="server" OnCommand="OpenLogin_Click"
                            ToolTip="Google_Login" CssClass="btngoogle"
                            CommandArgument="https://www.google.com/accounts/o8/id" Height="34px"
                            Width="143px" />
  <a id="btngmaillogout" runat="server" onserverclick="btngmaillogout_click"> 
        <img src="http://accounts.google.com/logout" id="imggoogle" title="Google_LogOut" onerror="javascript:return showimage();" />
    </a>

 Add code in login.aspx.cs page

using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;

OpenIdRelyingParty openid = new OpenIdRelyingParty();
       
        protected void Page_Load(object sender, EventArgs e)
        {
                HandleOpenIDProviderResponse();        
        }

        protected void HandleOpenIDProviderResponse()
        {          
                var response = openid.GetResponse();
              
                    if (response != null)
                    {
                        switch (response.Status)
                        {
                            case AuthenticationStatus.Authenticated:
                                NotLoggedIn.Visible = false;
                                btngmaillogout.Visible = true;

                                var fetchResponse = response.GetExtension<FetchResponse>();
                                Session["FetchResponse"] = fetchResponse;
                                var response2 = Session["FetchResponse"] as FetchResponse;

                                lblemail.Text = response2.GetAttributeValue(WellKnownAttributes.Contact.Email);
                                lblname.Text = GetFullname(response2.GetAttributeValue(WellKnownAttributes.Name.First),response2.GetAttributeValue(WellKnownAttributes.Name.Last));
                                lblbirthdate.Text = response2.GetAttributeValue(WellKnownAttributes.BirthDate.WholeBirthDate);
                                lblphone.Text = response2.GetAttributeValue(WellKnownAttributes.Contact.Phone.Mobile);
                                lblgender.Text = response2.GetAttributeValue(WellKnownAttributes.Person.Gender);
                                break;
                            case AuthenticationStatus.Canceled:
                                lblAlertMsg.Text = "Cancelled.";
                                break;
                            case AuthenticationStatus.Failed:
                                lblAlertMsg.Text = "Login Failed.";
                                break;
                        }
                    }
                    else
                    {
                        return;
                    }
        }

        protected void OpenLogin_Click(object src, CommandEventArgs e)
        {
            string discoveryUri = e.CommandArgument.ToString();
            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);
            fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last);
            fetchRequest.Attributes.AddRequired(WellKnownAttributes.Person.Gender);
            fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Phone.Mobile);
            fetchRequest.Attributes.AddRequired(WellKnownAttributes.BirthDate.WholeBirthDate);
            req.AddExtension(fetchRequest);
            req.RedirectToProvider();
        }

        private static string GetFullname(string first, string last)
        {
            var _first = first ?? "";
            var _last = last ?? "";
            if (string.IsNullOrEmpty(_first) || string.IsNullOrEmpty(_last))
                return "";
            return _first + " " + _last;
        }

        protected void btngmaillogout_click(object sender, EventArgs e)
        {
           // logout from gmail and return to website default/home page    
            Response.Redirect("~/Default.aspx");        
        }

Download Files  google_login.rar

That’s it! Execute the page and see it in action.
Now you can easily access gmail logged in user details in your asp.net website. If you have any query, please feel free to ask.


102 comments:

  1. It's really very nice post.I was looking for it. Thanks

    ReplyDelete
  2. send MAIL via web application with any mail account eg:-gmail. ......
    Check code snippet here
    http://techterabyte.blogspot.in/

    ReplyDelete
  3. Really a nice and useful post i was looking for this kind of stuff from long time.. thank you.

    ReplyDelete
  4. Sir it is very very nice post.so many days i tried for it.but i will get this now only thank you so much for it.And one think i want Clarify.it only display mailId and first name and last name but it would not display gender,dob like this.i want dob and gender.how to modify that code.

    ReplyDelete
  5. Thanks. Its user's private details. you can display those details only by user's permissions.

    ReplyDelete
    Replies
    1. Hi

      I have used your code as such but i am getting exception as
      "The message expired at 3/12/2013 6:46:04 AM and it is now 3/12/2013 1:32:36 PM."

      Stack Trace:
      at DotNetOpenAuth.Messaging.Bindings.StandardExpirationBindingElement.ProcessIncomingMessage(IProtocolMessage message)
      at DotNetOpenAuth.Messaging.Channel.ProcessIncomingMessage(IProtocolMessage message)
      at DotNetOpenAuth.OpenId.ChannelElements.OpenIdChannel.ProcessIncomingMessage(IProtocolMessage message)
      at DotNetOpenAuth.Messaging.Channel.ReadFromRequest(HttpRequestInfo httpRequest)
      at DotNetOpenAuth.OpenId.RelyingParty.OpenIdRelyingParty.GetResponse(HttpRequestInfo httpRequestInfo)

      Delete
    2. Hi,

      i also run my code after getting your post but i did not find any exception.

      Delete
    3. can you provide me zip files to download which will be useful foe me to proceed

      Delete
    4. @Ruchi i have solved that issue by changing the time settings of my system.. but now i am getting error as

      "This message has already been processed. This could indicate a replay attack in progress"

      Delete
    5. I have already attached download files with my post. Please check that.

      @exception - may be due to cache, just clear your browser cookies and cache.

      Delete
    6. HI it is very nice sample, I like it, but my requirement bit different, i would to know the email which has logged in the browser already.

      I mean when run my application I need to get email id which is already logged in that particularly.

      i would appreciate u help, as I stuck here from few days. could please help to overcome

      Delete
    7. I wnat to get email contact list also....so please help me.

      Delete
    8. if you still not finding the solution then contact me vbebins@gmail.com

      Delete
  6. thank you very much :) really very helpful

    ReplyDelete
  7. Hi i tried but only Firstname and Email id Fetchnig
    what abt Mobile and Address and DOB

    ReplyDelete
  8. its not fetching
    please give some suggetions and really very helpful thanks

    ReplyDelete
    Replies
    1. Mobile and address are the private details of user, we can not fetch these details.

      thanks....... :)

      Delete
  9. can we get address book using this?

    ReplyDelete
  10. how to get all user information from gmail and store in my db ?

    ReplyDelete
  11. Its realy Nice post, I use it easily
    Thanx

    ReplyDelete
    Replies
    1. Its realy Nice post, I use it easily.
      But mobile ,gender and address is getting null.
      Thanx

      Delete
  12. I have applied Same Code In my application, But when every i try to login using google Account , it is asking for Grant for Permission to access data such email id and name,

    the request is popping up every time. I have done some goggling, and i find that we have option. approval_format = force. But I have no idea where should apply these property , Could please solution for me.

    Thanks and regards
    Santosh

    ReplyDelete
    Replies
    1. this has to be attached to the url you are passing to the request

      Delete
  13. Hi it is a nice post but me getting this error

    Could not load file or assembly 'google_login' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

    Can u please provide a SOLUTION to it

    ReplyDelete
  14. can i bypass the google login authentication at the google page? Meaning to say that, I have a login page, so the user id and password will be filled in at my login page, then the authentication will run backend without google login page to be popped up..

    Thanks,
    Nany

    ReplyDelete
  15. Hi,Good controlling and managing the website content in Web Design Cochin is a vital part of the website management and website development process. Thanks...........

    ReplyDelete
  16. Thanks for wonder full post. But, i am not able to get the Phone,DOB and other fields from gmail. i am getting only the emailID & Full name! Any idea?

    ReplyDelete
  17. how i can send link in gmail account for those users who login in my application.like jabong.com

    plz.. help me

    ReplyDelete
  18. I want to get contact list also.....

    ReplyDelete
  19. Hi sir... i am getting output as login failed.. plz anyone help me...

    ReplyDelete
  20. i need unique id when response come for authenticate
    ..

    ReplyDelete
  21. is it possible to integrate google account with asp.net.

    ReplyDelete
  22. Dear sir thnx for nice post..
    but there is two problem
    1> every time i'm login or logout your blog auto_responce process..
    2>i'm try it in my web application it reject my urlScan and geting error

    thnx

    ReplyDelete



  23. Thnx,sirjee
    It's well working in localhost but i'm trying implement in iis7.5 web server
    its geting 404 error , rejected by urlScan at time of response..
    help me to slove this problem..

    ReplyDelete
  24. Hi it is a nice post, in my application it is working fine ,

    but i want to redirect the page (default.aspx) when LOGIN FAILD

    how to redirect....



    ReplyDelete
  25. hi this post help me...but i get only full name, country, email id details. but i want phone no,gender,image also. though this i didnt get.
    please help me

    ReplyDelete
  26. I'm getting error Could not load file or assembly 'google_login' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

    ReplyDelete
  27. Hi Sayali..i also get same error..i just copy same code in new project and it works..you also do the same.,

    ReplyDelete
  28. really what a nice article with code it helped me a loot and saved time too
    you roccckkkk..:):):)

    ReplyDelete
  29. Thanks. Its user's private details. you can display those details only by user's permissions.
    Gmail Account Support

    ReplyDelete
    Replies
    1. how to set or enable the permission so that i can access contact number as well as date of birth...

      Delete
  30. How to get the image url and display it? Can any one please help me with the image.

    ReplyDelete
  31. Hi , i tried the code and its working fine..but it is displaying my name and email..i want to import my all gmail account contacts..then what to do..plz help me out from this ..

    ReplyDelete
  32. Hello, good morning

    I'm using your code for login in my application.
    But I can not access the phone number, date of birth and gender.
    (microzapple@gmail.com)

    ReplyDelete
  33. Wow, really very useful information. i like it. thanx for sharing.. keep posting. you are looking for Gmail Technical Support You can reach Acetecsupport at their Call Toll Free No +1-800-231-4635 For US/CA.

    ReplyDelete
  34. visit for more : http://webdeveloperrs.blogspot.in/

    ReplyDelete
  35. thank you very much for providing .It helps me great.It worked very nice.

    ReplyDelete
  36. Thanx i got perfect code to login gmail.

    ReplyDelete
  37. I am getting an error no 400 : following domain not registered with the google openid , when using this code in my website.

    ReplyDelete
  38. I am also getting the error. Please help as soon as possible. Has google changed its way of authentication

    ReplyDelete
  39. This comment has been removed by the author.

    ReplyDelete
  40. I am getting an error no 400 : following domain not registered with the google openid , when using this code in my website.

    ReplyDelete
  41. very nice thanks from
    aspdotnetnaresh.blogspot.com

    ReplyDelete
  42. Hi..Can u help me please.. I am getting error like "Server Error in '/' Application.

    Sequence contains no elements"
    Can u please me

    ReplyDelete
  43. I am getting error "No OpenID endpoint found.". Please help me

    ReplyDelete
  44. Getting same error "No OpenID endpoint found."
    Moreover I am using membership API to authentication and authorization ..

    ReplyDelete
  45. This is very nice blog and informative. I have searched many sites but was not able to get information same as your site. I really like the ideas and very intersting to read so much and Please Update and i would love to read more from your site
    Thanks


    gmail email login page

    ReplyDelete
  46. Hi I am Getting the error "No OpenID EndPoint Found" when i tried your code any changes needed for this.

    ReplyDelete
  47. When you move towards the official support page, there are a very few chances of getting a written guide. However, with the step-by-step instructions provided by them, you can do-it-yourself by just following them properly.http://800support.net/gmail-support/create-gmail-account/

    ReplyDelete
  48. NICE for giving a chance to share ideas for your comuty i really thanks for that great post.
    jhfkdfk
    giuijds
    kfkhf

    ReplyDelete
  49. Easy way to integrate Gmail account in ASP and dot net and find instant support.
    http://www.emailcustomerservice.co/

    ReplyDelete
  50. Are you facing problems with your Comcast Business email account? Than simply get help using toll free number facility. Ways to Get Help from Comcast

    ReplyDelete
  51. Right steps follow if you forget Facebook account password. Contact Us:- Help For Facebook Account Password Recovery

    ReplyDelete
  52. Efficiently recover suspended Skype account without facing any difficulty. Visit Here@:- Skype Help Number

    ReplyDelete
  53. 4 Things You Should Check First When Skype Does Not Work.Visit Here@:- Skype Phone Number

    ReplyDelete
  54. Skype toll free number service easily fix issues related to Skype account. If you facing any issue in Skype mail account than instantly solve it using help service number of Skype.Technical Support Service Phone Number

    ReplyDelete
  55. Using customer care service easily setup SBCglobal email account on my Android phone. Our support service members describe some simple steps to setup SBCglobal email on android phone .Simply setup my SBCglobal email on my Android phone

    ReplyDelete
  56. If are you using Outlook Email; when you send a attached file or document to outlook you cannot attached a file to outlook email . This seems to have happened all the sudden. If you don’t know how to solve this problem so contact our customer support team and visit our website we will help you.

    ReplyDelete
  57. Printers are a kind of electronic devices which transfers information like text and graphic to the paper. While working with any kind of printers you can come across with paper jam where a paper is stuck inside the printer and you get a paper jam error in it. If the problem still persists, contact our 24*7 HP Printer Experts helpline.

    ReplyDelete
  58. If you want remove your password from the computer or internet browser and secure your facebook account so our help you to remove your password in your pc call our excellent customer support team and visit our website.

    ReplyDelete
  59. The sending of messages among Skype users, and in some cases, prevents users from connecting to the service. It’s a technical issue but we will solve this now visit our website and connect with expert support team.

    ReplyDelete
  60. Facebook Messenger is a great app for people to communicate with friends and family who are on Facebook. Additionally, Messenger is emerging as a popular platform to interact with brands and services. If you want locate the App Store on your device. Tap on the search bar (the field located at the top), and type in "Facebook Messenger". Tap on the "Get" button. if you don't understand how to download. contact with expart support team and visit our website will help you.

    ReplyDelete
  61. You need a sign-in address and password from an organization that has a Skype for Business. If you’re already using Skype for Business on your desktop, then you can sign in with the credentials from your work or Gmail account. If you don't understand how to sign-in in to Skype so visit our website and contact with our team.

    ReplyDelete
  62. If you have issue how to fix Epson scanner-printer problems in windows 8? So we have following tips- Switch on the Epson printer and connect it to the Windows 8 system, Switch on your PC, Go to Desktop, Right-click on the Start button and click Control Panel, Click Hardware & Sound, In the Hardware & Sound window, click Devices and Printers. if these steps are not working visit our website or connect with expert team.

    ReplyDelete
  63. If you are facing problem with facebook authentication errors, so we tell you how to solve these types of errors, or you are not able to login to their Facebook page. Some said that they double checked the login credentials like username and password but are facing the same issue. Now visit our website and directly contact with our expert team they will help you.

    ReplyDelete
  64. When you are using yahoo mail account, sometimes you need to recover yahoo mail forgotten password. You are trying different ways but nothing worked, then you should contact with our support team for resolve it or you can also follow our website for some steps. We will help you.

    ReplyDelete
  65. System.InvalidOperationException: Sequence contains no elements
    I'm getting this error page kindly help me asp.

    ReplyDelete
  66. Skype provide various type of features like video call, voice call and file sharing without any kinds of trouble. And if want to stop Skype from Auto Boot on Windows 7 than follow these steps and easily get solution.Skype Tech Support Service Number

    ReplyDelete
  67. Academics
    School Hours are comprises of Hard and Soft Hours. Major academics are get covered in to hard hours – basic subjects (Hindi, Numbers and English) while in soft house kids enjoy Dance, Music Sports, Art and Craft. School hours are of 4 hours.

    http://www.sanskaarkidskingdom.com/

    ReplyDelete
  68. Taking into consideration the basic need to develop other co- curricular activities amongst these kids, Sanskaar Kids Kingdom organization has come up with some of the other involving activities so that the parents may also feel that the other opportunities can be availed by the kids at same center.

    http://www.sanskaarkidskingdom.com/lucknow/

    ReplyDelete
  69. Thanks Rakhi Aswal for sharing that kind of informaative stuff with us!
    if anyone facing problems in gmail login contact us 1-888-250-5995 and get quality services from our experts!

    ReplyDelete
  70. If you want to Setup your office product visit office setup.office.com/setup

    ReplyDelete
  71. Installing your Microsoft Office365 may be you can see the message like, Stop, you should wait to install Office 2016.www.office.com/setup

    ReplyDelete

  72. In case any message saying ‘Stop’ pops up while installing Microsoft Office 365 due to a compatibility issue, contact our live chat support.

    www.office.com/setup

    ReplyDelete