VZ-Login-Tutorial

From VZ Developer Wiki
Revision as of 17:31, 30 November 2010 by Seba (talk | contribs) (Step 7: Acces the user data)
Jump to: navigation, search

A Step-by-Step Guide to using VZ as Your Login Handler

Why VZ-ID?

If your website requires authenticated users which have to sign up in first place, this process is usually considered as a conversion killer. Users are more likely to sign up if they can use their already existing credentials. This is where VZ-ID comes into play. It offers an easy-to-use API which integrates with your website's user management. The following guide will describe how the integration can be achieved with a few lines of code.

The following guide was created using a MeinVZ developer account, but it will work for the other platforms in the same fashion.

Step 1: Go to the developer section

Before you can integrate VZ-ID you are required to sign in as a developer on either one of the following platforms: StudiVZ, MeinVZ or SchülerVZ. Your account will be activated after it went though our validation and approval process.

Step 2: Create a new service

Before you can use the API, you will be requested to create a "service" which contains information about your website that is about to use VZ-ID.

  • Service Name is just an identifier to help you to identify your current website among other websites and services you already created or you might create in future
  • Description describes the nature of your website
  • Callback URL must be an accessible URL within your domain. You will copy an HTML file there which will be provided later in this tutorial

Step1.png

Step 3: Get your key and secret

A successfully completed service creation will guide you to the following interface. It shows all credentials which you will need in order to integrate VZ-ID with your website.

  • Copy your key and your secret to the clipboard, you will need it during the next step.

Step2.png

The key and the secret are unique. Do not give away the secret of your website at any time and make sure not to use it in JS code since it would enable others to spoof your website's identity.

Step 4: Start coding

The following code snipplet represents the part of your website where you want to include the "VZ Login" button which opens a popup where the user can enter his VZ credentials. After a login, the callback function 'logResponse()' will be executed in order to pass the access token and other useful information to your code by setting a cookie.

<?php
    $consumerKey = 'consumer key';
    $consumerSecret = 'consumer secret';
    $cookieKey = 'vz_' . $consumerKey;
    $requiredFields = array('name', 'emails');
    $callbackUrl = 'http://path/to/vzid-democlient/callback.html';
    $redirectUrl = 'http://path/to/vzid-democlient/completed.php';
?>
<html>
    <head>
        <title>Index</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <script src="http://static.pe.studivz.net/Js/id/v2/library.js"
        data-authority="platform-redirect.vz-modules.net/r"
        data-authorityssl="platform-redirect.vz-modules.net/r" type="text/javascript">
        </script>
    </body>
    <script type="text/javascript">
    function logResponse(c) {
        if (c.error) {
            console.log(c);
            return;
        }

        var parameters = 'access_token=' + c.access_token;
        parameters += '&user_id=' + c.user_id;
        parameters += '&signature=' + c.signature;
        parameters += '&issued_at=' + c.issued_at;

        document.cookie = '<?php echo $cookieKey ?>' + '=' +  encodeURIComponent(parameters);
        document.location.href = '<?php echo $redirectUrl ?>';
    }
    </script>
    
    <script type="vz/login">
       client_id : <?php echo $consumerKey . PHP_EOL ?>
       redirect_uri : <?php echo $callbackUrl . PHP_EOL ?>
       callback : logResponse
       fields : <?php echo implode(',', $requiredFields) . PHP_EOL ?>
    </script>
</html>

Step 5: Copy + paste the callback.html

This file is required to be opened within the popup window. It only passes the login data to its parent window where the code from step 4 is running. Please save this file as 'callback.html' or modify the code from step 4 accordingly.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Callback</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
      <script type="text/javascript">
        opener.vz.id.authStorage.setAuthParameterHash(location.hash.substr(1));
        window.close();
      </script>
  </body>
</html>

Step 6: Verify the returned data!

You might ask, why you should do this? You received data from an external source which might pretend to be the VZ server. This is not very likely but still a security risk Verifying the data's accuracy is therefore obligatory. Since only VZ and you know your consumer secret, you are a few lines of code away from ensuring that the data you received has not been tempered. In the following snipplet we will create a checksum of all data transfered by signing it with your consumer secret. If that checksum equals the one provided in the response, you are safe. This operation can only be done in your backend since you would disclose your consumer secret otherwise.

<?php
    $consumerKey = 'consumer key';
    $consumerSecret = 'consumer secret';
    $cookieKey = 'vz_' . $consumerKey;


    if ($loggedInWithVzId = isset($_COOKIE[$cookieKey])) {
        // check if VZ-ID cookie exists and is valid
        $cookie = array();
        parse_str($_COOKIE[$cookieKey], $cookie);

        $baseString = $cookie['access_token'] . $cookie['issued_at'] . $cookie['user_id'];
        $signature = base64_encode(hash_hmac('sha1', $baseString, $consumerSecret, true));
        $retrievedSignature = $cookie['signature'];

        // check if given signature equals calculated signature which used the
        // consumer secret in order to avoid user id manipulation
        if ($signature !== $retrievedSignature) {
            throw new Exception('invalid cookie signature');
        }
    }   
?>

Step 7: Acces the user data

The following snipplet verifies if the user successfully logged in using VZ-ID. It also fetches the user's vCard data by accessing our OpenSocial Gadgets_REST_People People API. This is achieved by sending a REST call with the access token attached.

<html>
    <head>
        <title>Registration</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
       <?php if ($loggedInWithVzId): ?>
        <h1>Successuflly logged in with VZ-ID</h1>
        <?php

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $cookie['user_id'] . '?oauth_token=' . $cookie['access_token']);
        curl_setopt($ch, CURLOPT_HTTPGET, true);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $ret = curl_exec($ch);
        curl_close($ch);

        $userData = json_decode($ret, true);
        var_dump($userData['entry']);
        ?>
       <?php else: ?>
        <h1>Please register or log in</h1>
        <!--
       <?php endif ?>
    </body>
</html>