Implementation of Token Based Authentication

###What is token based authentication

Token-based authentication is a method to authenticate user access to the specific resources with a valid token that is generated by the server only if user provided a correct username and password.

###Steps to implement a simple token-based authentication example

a)    Create customer database
b)    Unique token generator
c)    Implements customer login operation
d)    Authentication

###Create a customer database

Create table customer  (
  customer_id int(11) not null AUTO_INCREMENT,
  username varchar(255) unique not null,
  password varchar(255) not null,
  token varchar(255),
  expired varchar(100),
  ip varchar(255),
  primary key (customer_id)
);

Add a customer:

Insert into customer(username, password) values("admin", "123456");

###Unique token generator

We need a method to generate unique token for different customers. The token is composed by three parts: machine id, timestamp and unique id.

//generate token
function generate_token(){
  $date = new DateTime();
  $token = $date->getTimestamp();
  //if we have multiple server, we need to assign different prefix to each one
  $token = uniqid('server1', true);       
 return $token;
}

###Customer login

<?php
  error_reporting(E_ALL);
  ini_set('display_errors', 1);

  //get username and password
  $username = $_POST['username'];
  $password = $_POST['password'];
  $ip = $_SERVER['REMOTE_ADDR'];

 //generate token
function generate_token(){
  $date = new DateTime();
  $token = $date->getTimestamp();
  $token = $token . uniqid('server1', true);       //if we have multiple server, we need to assign different prefix to each one
  return $token;
}

//connect database
try {
  $pdo = new PDO('mysql:host=localhost;dbname=project1', "project1", "0WkWy2dIHhcLfLKs");

  $sql = "select * from customer where username=:username and password=:password";
  $sth = $pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
  $sth->execute(array(':username' => $username, ':password' => $password));
  $customer = $sth->fetchAll();

  if(count($customer) == 0){

    echo "username or password not correct";
    die();

  }else{

    $customer = $customer[0];
    $customer_id = $customer['customer_id'];
    $token = generate_token();

    //expired after 24 hours
    $date = new DateTime();
    $date->add(new DateInterval('PT24H'));

    $sql = "update customer set token=:token, ip=:ip, expired=:expired where customer_id=:customer_id";
    $sth = $pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
    $sth->execute(
        array(
            ':token' => $token,
            ':ip' => $ip,
            ':expired' => $date->getTimestamp(),
            ':customer_id' => $customer_id
        )
    );

    echo "token : " . $token;
  }

  $dbh = null;
  } catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

###Authentication by token

<?php
  //check user token
  $token = $_POST['token'];
  $ip = $_SERVER['REMOTE_ADDR'];

 //current timestamp
 $date = new DateTime();
 $timestamp = $date->getTimestamp();

 //connect database
 try {
   $pdo = new PDO('mysql:host=localhost;dbname=project1', "project1", "0WkWy2dIHhcLfLKs");

   $sql = "select * from customer where token=:token and ip=:ip and expired > :timestamp";
   $sth = $pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
   $sth->execute(array(':token' => $token, ':ip' => $ip, ':timestamp' => $timestamp));
   $customer = $sth->fetchAll();

   if(count($customer) == 0){

     echo "you haven't login system";
     die();

   } else {

     $customer = $customer[0];
     $username = $customer['username'];

     echo "you are : " . $username;
  }

} catch (PDOException $e) {
  print "Error!: " . $e->getMessage() . "<br/>";
  die();
}

By checking IP address and expired time, an illegal token can be prevented to access the system.

Build a Local PHP Development Environment

PHP is a widely-used, free, server scripting language, and a powerful tool for making dynamic and interactive Web pages. I will show how to build a local PHP development environment

  1. Set up LNMP
    We use the integrated installation package for our development environment.
    Create a folder named source under /home, we will put all sources file in this folder.
    and start setup the lnmp

    mkdir /home/source

    cd /home/source
    

    wget -c http://soft.vpser.net/lnmp/lnmp1.3-full.tar.gz
    tar zxf lnmp1.3-full.tar.gz && cd lnmp1.3-full
    ./install.sh lnmp

    • given the mysql root password:jXS90VERcZqqE7XP
    • yes to install InnoDB
    • select the MySQKL 5.7.11
    • use PHP 7.0.7
    • use TCMalloc as memory allocator

      App Store

      App Store

      Now we finished the installation of LNMP.

  2. Create a domain on host machine

    a. Run notepad by administrator privilege

    b. Open hosts file: C:\Windows\System32\drivers\etc\hosts

    App Store

    c. Add a domain mapping to virtual machine. We will use this domain to access our website. The IP address of virtual machine is 192.168.183.132, and I take the domain “project1.abc.com” for first project.

    App Store

  3. LNMP operations

    a) create a new website

    commend: lnmp vhost {add|list|del}

    let’s create a website: project1.abc.com
    run commend “lnmp vhost add”, input the domain for website “project1.abc.com”,

    App Store

    Create database for my website

    • name: project1
    • user: project1
    • password: 0WkWy2dIHhcLfLKs

    App Store

    Press any key to start create virtual host

    App Store

    Now, we write an index.php file with following content
    vim /home/wwwroot/project1.abc.com/index.php

    App Store

    Now, we can access the website on host machine by http://project1.abc.com/

    App Store

    b) LNMP status management

    lnmp {restart | start |stop}

    App Store

    c) MySQL status management

    /etc/init.d/mysql {start|stop|restart|reload|force-reload|status}

    d) Nginx status management

    /etc/init.d/nginx {start|stop|reload|restart}

  4. Operation MySQL on host machine
    a. allow all machine access database by root

    execute mysql –u root –p, and give the password to login mysql

    use mysql database, and execute update statement.

    App Store

    b. restart the LNMP

    App Store

    c. open MySQL Workbench on host machine, create a new server. Give a name for the server, and provide the username, password, and port.

    App Store

    Press test connection

    App Store

    Ok, MySQL database connected. Press “OK” to save the server information.

    click the server block, then we can operate the database now
    App Store

    Now, we can add this server to Phpstorm as remote server. Write code on windows and run in centos.

Create a CentOS Virtual Machine in VMWare Station

I have been using Virtual Box in development for several years. Really like its simplicity and easy of use. Recently, I worked on a project that used VMWare Station as development enviroment. Here I am go to documentment how to create a CentOS virtual machine in VMWare Station.

Click File -> New Virtual Machine, click “next”’

App Store

Choose the path of the CentOS image file, click “next”

App Store

Give a name for you virtual machine, and select a path to store all files. click “next”

App Store

Modify the maximum disk size to 40gb, and click next, and next.

App Store

Now start installation of centos system. Just select “Install CentOS 7” and press enter

App Store

Select the language you prefer

App Store

Select installation destination, click “installation destination”, and click “done” to use default configuration.

App Store

App Store

Click the “software selection”, we use GNODE Desktop here, and click “done”

App Store

Then click “Begin Installation”
Now set the password for root

App Store

App Store

After all finished, click Reboot