martedì 30 ottobre 2012

Registrazione al sito tramite Google Login

Ottenere informazioni da Google per la registrazione degli utenti al nostro sito è una pratica abbastanza facile. Io personalmente ci ho sbattuto la testa per un giorno, perché cercando su internet ho trovato migliaia di versioni, una più complicata dell'altra. Qualcuno aveva persino consigliato di scaricare l'intera libreria SDK di google per C#, da ben 27 mega! Altri rispondevano con cose quasi surreali, o con pezzi di codice palesemente errati.
Ovviamente quello che leggerete qui è una sintesi, e va adattata alle vostre esigenze. Vi riporterò i link della documentazione ufficiale che in ogni caso vi conviene leggere.

Il succo del succo è questo: registrate una nuova applicazione nella Google Api Console, inserendo un vostro dominio (anche localhost per provare) e il percorso della pagina che riceverà i dati da Google.
Creare un link in una vostra pagina con un indirizzo particolare che scriverò sotto.
Tramite questo link google chiederà le autorizzazioni all'utente e vi ritornerà (alla pagina che avete impostato) un token.
Prendete quindi questo token e tramite una chiamata al webservice di Google otterrete le informazioni dell'utente. 

Prima di tutto dovete registrare una nuova applicazione nelle Google Api Console, e cominciare a leggere i link della documentazione ufficiale:

<%--
First of ALL: Register an Application on Google Api Console
GOOGLE API CONSOLE:

DESCRIZIONE IN GENERALE:

DESCRIZIONE PER IL LOGIN:
 --%>

Poi è la volta del link.

<%-- Qui alcune informazioni sui parametri da passare che comporranno il link
First: Click to connect to google
        
response_type = Determines if the Google Authorization Server returns an authorization code, or an opaque access token.
client_id     = Indicates the client that is making the request. The value passed in this parameter must exactly match the value shown in the APIs Console.
redirect_uri  = Determines where the response is sent. The value of this parameter must exactly match one of the values registered in the APIs Console (including the http or https schemes, case, and trailing '/').
scope         = Indicates the Google API access your application is requesting. The values passed in this parameter inform the consent page shown to the user. There is an inverse relationship between the number of permissions requested and the likelihood of obtaining user consent.
state         = This optional parameter indicates any state which may be useful to your application upon receipt of the response. The Google Authorization Server roundtrips this parameter, so your application receives the same value it sent. Possible uses include redirecting the user to the correct resource in your site, nonces, and cross-site-request-forgery mitigations.
 --%>

Il link sarà del tipo:
Login con Google

Leggete bene a cosa servono tutti questi parametri e notate che lo scope deve essere decodificato correttamente. 
userinfo.email vi permette di ricevere le informazioni sull'email oltre a quelle del profilo ottenute da userinfo.profile.

In questo caso il link è sulla pagina LoginGoogle.aspx e il redirect è sulla stessa pagina. Quindi Google  invierà il token in querystring alla stessa pagina.

Poi è la volta della chiamata al webservice. Magari sarà in un'altra pagina, in ogni caso deve essere solo un esempio da adattare. Mi sono aiutato con JQuery e ho scritto nei commenti tutti i valori che ritorna google. Utilizzate i valori che vi ritorna per le vostre esigenze.
Il token è preso dalla querystring con la funzione che c'è all'inizio dello script e non con Request.Querystring in JS come scrivono in molti!

<%--    
Second: Click to get the Token from querystring and connect again to google to request user information.
--%>

       <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>

        <script language="javascript" type="text/javascript">

        // First, parse the query string (In Js does not exists Request.QueryString!)
        var params = {}, queryString = location.hash.substring(1),
            regex = /([^&=]+)=([^&]*)/g, m;
        while (m = regex.exec(queryString)) {
          params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
        }

        //All that returns Google
        var token = params['access_token'];         //access token to your application if the user grants your application the permissions it requested
        var state = params['state'];                //If the state parameter was included in the request, then it is also included in the response.
        var token_type = params['token_type'];      // kind of token that is being returned
        var expires_in = params['expires_in'];      //lifetime of the token in seconds

        //Call Google Webservice
        $(document).ready(function () {

            $.ajax({
                type: "GET",
                url: "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token,
                crossDomain: true,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                //async: false,
                success: function (result) {

                    var id = result.id;                             //The value of this field is an immutable identifier for the logged-in user, and may be used when creating and managing user sessions in your application. This identifier is the same regardless of the client_id. This provides the ability to correlate profile information across multiple applications in the same organization. The value of this field is the same as the value of the userid field returned by the TokenInfo endpoint.
                    var email = result.email;                       //The email address of the logged in user
                    var verified_email = result.verified_email;     //A flag that indicates whether or not Google has been able to verify the email address.
                    var name = result.name;                         //The full name of the logged in user
                    var given_name = result.given_name;             //The first name of the logged in user
                    var family_name = result.family_name;           //The last name of the logged in user
                    var picture = result.picture;                   //The URL to the user's profile picture. If the user has no public profile, this field is not included.
                    var locale = result.locale;                     //The user's registered locale. If the user has no public profile, this field is not included.
                    var timezone = result.timezone;                 //The default timezone of the logged in user
                    var gender = result.gender;                     //The gender of the logged in user (other|female|male)

                    alert(gender);

                    //$('#txtCheckUsername').val(result.d);

                },
                error: function (result) {
                    alert('Error...');
                }
            });


        });

        </script>

       

Nessun commento: