php


Table of Contents:

Prerequisites
Php SDK Installation
Run the php Demo App
Creating your own php App


Prerequisites


Creating an app involves two basic steps:

  1. Register/create an app in the portal and obtain credentials (this is detailed in the 'Register / Create a New App' menu section)
  2. Configure your app using an SDK, making use of these credentials

It is recommended that you first create a demo/test app with a redirect uri of http://127.0.0.1:5000/login in the portal, to enable you to run the SDK demo app and test the SDK functionality.

In the portal, when you create a new app, you will be issued with the Client ID and Client Secret credentials that you need to specify when building your app with the SDK. Note that your Client Secret will only be issued to you once so it must be grabbed when first displayed:

client secret

Client ID can then be copied at any time from the app settings screen:

app settings page

Note that you can control the Login Methods available (QR Code requires customer usage of the mobile app. While Browser Login enables logging in within the desktop browser, without the mobile app)

When creating your app in the portal, you also must specify a redirect_uri endpoint which comes from the url where you are hosting your app:

add app

The SDK will automatically create the redirect uri by appending '/login' to your url. You, of course, are in charge of what the base url of your app is. So it could be http://testapp.com/login, http://12.34.567.89:8080/login or http://127.0.0.1:5000/login as above. Note, however, that the MFA server will not accept 'localhost' as a base url.


Php SDK Installation


  1. Dependencies:

    • Php version 5.6+
    • Composer (as from https://getcomposer.org/download/)
    • sudo apt-get install php7.0-curl
    • sudo apt-get install php-sqlite3
    • sudo apt-get install php7.0-xml
    • sudo apt-get install php7.0-intl
      Note - the above assumes php version 7 is installed
  2. Download or clone the SDK from:

    https://github.com/miracl/maas-sdk-php

  3. Install the SDK:

    Go to the root directory: cd maas-sdk-php

    Install with composer: composer install
    Or, if you have not installed composer globally: php composer.phar install


Run the php demo app


Running the pre-configured demo app will help you make sure that you have all your settings correct and so will be able to proceed with confidence toward developing your own application:

  1. Open the src/miracl.json file and configure with your client id, client secret and redirect_uri values, as set up in the Create a New App menu section.

    For security, the client ID and secret for a genuine app should not be stored in clear text in a config file. This has only been done here for simple demo purposes. For a production scenario, the client ID and secret should be programmatically accessed via an encrypted API

    {
    "client_id": "CLIENT_ID",
    "secret": "SECRET",
    "redirect_uri": "http://127.0.0.1:5000/login",
    "miracl_base_url": "https://api.mpin.io",
        "proxy": ""
    }  

    Substitute CLIENT_ID, CLIENT_SECRET and REDIRECT_URI with your correct values.

    Note that, at this point, you can also add a proxy server, and the app will work through the specified server.

  2. Open the templates/main.php file and, towards the end of the file, make sure the mpad script has the correct url in order to communicate with the authentication server (note that it begins with 'mcl.cdn.mpin.io'):

    <script src="https://mcl.cdn.mpin.io/mpad/mpad.js" data-authurl="<?= $authURL ?>" data-element="btmpin"></script>
  3. From the src directory, run the server with a simple php server command:

    php -S 127.0.0.1:5000 -t .

    This server command will mean your demo app is running at http://127.0.0.1:5000/. This means that a redirect_uri value of http://127.0.0.1:5000/login will function correctly. If you wish to change this, just edit the above command, but remember it must match what has been entered in your app details screen in the portal.

    Now you can visit the url in your browser and test the app:

    php login

    From here you will be prompted to:

    1. Register
    2. Key in your identity
    3. Confirm your identity (by email activation)
    4. Create a 4-digit PIN:
    5. Login

    Once logged in you will be greeted by the refresh/logout page:

    php logged in


Creating your own php app


What follows is a detailed breakdown of the structure and code used in creating the sample app, which will give you a broad understanding of how to begin creating your own app. Note that the snippets of code which follow can be put to use, and you can also find the full files in the maas-sdk-php root folder.

The basic components, as per the sample app, are:

  • a templates/main.php file to create a main web page with the login button
  • a .json credentials file
  • an index.php script to contain the code for dealing with the Miracl Client object and communicate with the platform

It is important to have these files in your root folder to enable communication with the core SDK files (MiraclCLient.php MiraclConfig.php and composer.json)

The instructions to follow will guide you on how to create your own app which gives complete management of the authorization flow.

1. Create the main web page and the login button

Note that the use of col-md divs here assumes use of the bootstrap framework, as does the use of <?php if (isset($) { ?> to receive flash messages in the standard bootstrap categories of 'success', 'info' and 'danger'.

In your templates/main.php file, listen for messages coming from your main index.php script:

<div class="row">
    <div class="col-md-12">
        <?php if (isset($messages)) {
            foreach ($messages as $m) { ?>
                <div class="alert alert-<?= $m['category'] ?>">
                    <?= $m['text'] ?>
                </div>
            <?php }
        } ?>
    </div>
</div>

Then run an if (isset($retry)) to check for the retry message coming from your main script. The retry message means that an attempted login has failed (as will be seen later) and your script will have provided an authorization url. In this case a btmpin div is created to contain the login button (note that the wording for this is automatically populated by mpad.js hence there is no text entered in the btmpin div):

<?php if (isset($retry)) { ?>
  <div class="col-md-12">
      <div id="btmpin"></div>
</div>

The next if if (isset($isAuthorized) && $isAuthorized) check is to listen for the isAuthorized message, in which case display refresh or logout buttons which initiate a redirect to the "refresh" and "logout" endpoints:

<?php } else { ?>
    <div class="row">
        <?php if (isset($isAuthorized) && $isAuthorized) { ?>
            <div class="col-md-4">
                <b>E-mail:</b> <?= $email ?><br/>
                <b>User ID:</b> <?= $userID ?><br/>
            </div>
            <div class="col-md-4"></div>
            <div class="col-md-4">
                <a href="?refresh" class="btn btn-primary action">Refresh</a>
                <a href="?logout" class="btn btn-primary action">Log out</a>
            </div>
        <?php } else { ?>
            <div class="col-md-12">
                <div id="btmpin"></div>
            </div>
        <?php } ?>
    </div>
<?php } ?>

The last else section of the above snippet then creates a btmpin div to contain the login button (note that the wording for this is automatically populated by mpad.js hence there is no text entered in the btmpin div).

Finally, just before the closing tag, create the button itself:

<?php if (isset($authURL)) { ?>
    <script src="https://mcl.cdn.mpin.io/mpad/mpad.js" data-authurl="<?= $authURL ?>" data-element="btmpin"></script>
<?php } ?>

This makes use of the mpad.js library to send the authentication information to the server:

The parameters passed in this script are:

  • data-element: the login button ID (corresponds with <div id="btmpin">)
  • data-authurl: the authorization URL (this passes the client_id and redirect_uri to the authentication server). Each SDK has a 'Get Authorization Request URL' method for obtaining this.

2. Create the credentials file

For security, the client ID and secret for a genuine app should not be stored in clear text in a config file. This has only been done here for simple demo purposes. For a production scenario, the client ID and secret should be programmatically accessed via an encrypted API

In the root folder, create a file named miracl.json to store the credentials for your app:

{
    "client_id": "CLIENT_ID",
    "secret": "SECRET",
    "redirect_uri": "REDIRECT_URI",
    "miracl_base_url": "https://api.mpin.io",
    "proxy": ""
}

Substitute the correct values for your app, as discussed in 'Prerequisites' above.

Note that, at this point, you can also add a proxy server, and the app will work through the specified server.

3. Create the main server script

Now create a main index.php script, with the following main elements:

  1. Requires Include the composer autoload require at the top of your script:

    require "./vendor/autoload.php";
    require 'util.php';
  2. Read Credentials
    Now read the credentials from the json file and use to initialize the Miracl Client:

    $config = json_decode(file_get_contents("miracl.json"),true);
    
    $miracl = new \Com\Miracl\MaasSdk\MiraclClient(
    $config['client_id'],
    $config['secret'],
    $config['redirect_uri'],
    $config['miracl_base_url'],
    $config['proxy']
    );  
  3. Set up message handling for communication with main.php template

    Create an array which can be used to send messages to the template:

    $data = array();
  4. Dealing with the Miracl Client / Managing the Authorization Flow

    Now run checks for user interaction with the button and authentication status.

    First, if the user is logged in, you can check if they have requested logout, in which case make use of the $miracl->logout() method:

    if (isset($_REQUEST['logout'])) {
      // Save message in session
      flashMessage("info", "User logged out!");
      $miracl->logout();
      // Send redirect to client page reload
      header("Location: .");
      // End output here
      die();

    Or the $miracl->refreshUserData() data method can be called.

    Note that refresh clears userInfo from the session, but leaves the access token unchanged. This means that user info can be requested without performing a fresh authorization.

    } else if (isset($_REQUEST['refresh'])) {
      $miracl->refreshUserData();
      // Send redirect to client page reload
      header("Location: .");
      // End output here
      die();
    }

    After a user has made a login attempt, use the $miracl->validateAuthorization() method to check if their login attempt has been successful and send either a success message if successful, or a danger message and a retry message if login has failed:

    else {
      // Reload page if authorization happened just now
      if (isset($_REQUEST['code'])) {
          // Validate authorization
          if ($miracl->validateAuthorization()) {
              // Save success message in session
              flashMessage("success", "Successfully logged in!");
          }
          else {
              // Save fail message in session
              flashMessage("danger", "Login failed!");
          }
          // Send redirect to client page reload
          header("Location: .");
          // End output here
          die();
      }
      // Populate model for template
      if ($miracl->isLoggedIn()) {
          $data['isAuthorized'] = true;
          $data['email'] = $miracl->getEmail();
          $data['userID'] = $miracl->getUserID();
      } else {
          $data["authURL"] = $miracl->getAuthURL();
      }
    }

    If the $miracl->isLoggedIn() method returns true, an access token is available, the isAuthorized message is sent to the page template, and the $miracl->getEmail() and $miracl->getUserID() methods can be used to retrieve user details.

    Important Note on User Management

    In terms of managing your users, it is important to note that, in the process of providing a secure login solution, the service has also registered your users with a confirmed user email and user ID. Once a user has been authenticated it is possible to make use of the above $miracl->getEmail() and $miracl->getUserID() methods to return string values.

    This removes a considerable amount of pain from the process of managing users and databases!

    For example, if you have a SQL user database and you want to make a check to see if a user is present, or needs added as a new user, then it is possible to make use of the above methods.

    Another example would be if you want to present a web form to capture more information that is needed to provide a user with access to your product features. Here you can use the above methods to prepopulate the ID and email address field, and you do not need to initiate a 'verify by email' process, as this has already been done by the service.

    Now add messages to the array:

    if (isset($_SESSION["messages"])) {
      $data["messages"] = $_SESSION["messages"];
      $_SESSION["messages"] = array();
    }

    Use the array to render the template and output to the client (note that categories are according to the default Bootstrap categories of success, info, warning, danger):

    echo renderTemplate("main", $data);

    Note that util.php contains the functions to send the messages to the client and render the template:

    function flashMessage($category, $message)
    {
        $_SESSION['messages'][] = array(
            'category' => $category,
            'text' => $message
        );
    }
    
    function renderTemplate($name, $vars)
    {
        ob_start();
        extract($vars);
        include '../templates/'.$name.'.php';
        return ob_get_clean();
    }

Top