Showing posts with label google api access. Show all posts
Showing posts with label google api access. Show all posts

Monday, 11 February 2013

Google Plus Authentication in asp.net and c#

How to get google api access:


1. Open https://code.google.com/apis/console/?pli=1
2. Login by your gmail account.
3. Click on API Access option from left side.

 4. Click Create an OAuth 2.0 client ID.. button.
 5. It will open a dialog box.
6. Set Product Name (example: test), Product Logo (optional), Home Page URL (example: http://localhost/website/Default.aspx).
7. Click Next by filling all above information. It will open Next window.

8. Click Create client ID. It will give Branding Information.
9. Redirect URIs is blank in above image. Click on Edit Settings.. from right side vertical menu.
10. It will open a new window to fill Authorized Redirect URIs . It may be same url as Home page url, example: http:localhost/website/default.aspx. Leave Authorized JavaScript Origins as blank.

By above steps, you will get Client ID and Redirect URIs that will be used in further steps.


ASP.Net application:

In below code, first set your Client ID and Redirect URI.

I have given example to show logged in Username and profile image, you can use it in any other way also.
In function getUserInfo(), you can get result as username, email and etc..
jQuery Link: jQuery.js
If you get any issue to find above jQuery file, please mail me at vdtrip@gmail.com .

<HTML><Head>


 <script src="jquery.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
var OAUTHURL    =   'https://accounts.google.com/o/oauth2/auth?';
        var VALIDURL    =   'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
        var SCOPE       =   'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email';
        var CLIENTID    =   '13226233322131.apps.googleusercontent.com';
        var REDIRECT = 'http://localhost/WebSite/default.aspx';
        var LOGOUT      =   'http://accounts.google.com/Logout';
        var TYPE        =   'token';
        var _url        =   OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
        var acToken;
        var tokenType;
        var expiresIn;
        var user;
        var loggedIn    =   false;

   
        function login() {
            var win         =   window.open(_url, "windowname1", 'width=800, height=600');

            var pollTimer   =   window.setInterval(function() {
                try {
                    console.log(win.document.URL);
                    if (win.document.URL.indexOf(REDIRECT) != -1) {
                        window.clearInterval(pollTimer);
                        var url =   win.document.URL;
                        acToken =   gup(url, 'access_token');
                        tokenType = gup(url, 'token_type');
                        expiresIn = gup(url, 'expires_in');
                        win.close();

                        validateToken(acToken);
                    }
                } catch(e) {
                }
            }, 500);
        }

        function validateToken(token) {
            $.ajax({
                url: VALIDURL + token,
                data: null,
                success: function(responseText){ 
                    getUserInfo();
                    loggedIn = true;
                    $('#loginText').hide();
                    $('#logoutText').show();
                }, 
                dataType: "jsonp" 
            });
        }

        function getUserInfo() {
            $.ajax({
                url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
                data: null,
                success: function(resp) {
                    user    =   resp;
                    console.log(user);
                    $('#uName').text('Welcome ' + user.name);
                    $('#imgHolder').attr('src', user.picture);
                },
                dataType: "jsonp"
            });
        }

        //credits: http://www.netlobo.com/url_query_string_javascript.html
        function gup(url, name) {
            name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
            var regexS = "[\\#&]"+name+"=([^&#]*)";
            var regex = new RegExp( regexS );
            var results = regex.exec( url );
            if( results == null )
                return "";
            else
                return results[1];
        }

        function startLogoutPolling() {
            $('#loginText').show();
            $('#logoutText').hide();
            loggedIn = false;
            $('#uName').text('Welcome ');
            $('#imgHolder').attr('src', 'none.jpg');
        }
  

</script>
</Head>
<body>
 <a href='#' onClick='login();' id="loginText"'> Google Plus </a>
  <a href="#" style="display:none" id="logoutText" target='myIFrame' onclick="myIFrame.location='https://www.google.com/accounts/Logout'; startLogoutPolling();return false;"> Click here to logout </a>
    <iframe name='myIFrame' id="myIFrame" style='display:none'></iframe>
    <div id='uName'></div>
    <img src='' id='imgHolder'/>

</body>
</HTML>