Yii2 Rest Api with Username and Password


(Adi Apriyanto) #1

Create new table user_rest_api


CREATE TABLE `user_rest_api` (

	`id` INT(11) NOT NULL AUTO_INCREMENT,

	`username` VARCHAR(50) NOT NULL DEFAULT '0',

	`password` VARCHAR(50) NOT NULL DEFAULT '0',

	`token` VARCHAR(50) NOT NULL DEFAULT '0',

	PRIMARY KEY (`id`),

	INDEX `user` (`username`),

	INDEX `pass` (`password`)

)

COMMENT='Table user_rest_api\r\nby Adi Apriyanto\r\n13-6-2017'

COLLATE='utf8_general_ci'

ENGINE=InnoDB

AUTO_INCREMENT=16

;

Insert some data


INSERT INTO `user_rest_api` (`username`, `password`, `token`) VALUES ('demo', md5('demo'), '12345')

[font="Courier New"]

username : ‘demo’

password : ‘fe01ce2a7fbac8fafaed7c982a04e229’ (encrypt to md5 or define in model)

token : ‘12345’ (Free Random Value)

[/font]

Setting main config frontend/config/main.php


'urlManager' =>  [

            'rules'=>array(

                // RestApi

                ['class' => 'yii\rest\UrlRule', 'controller' => 'api', 'pluralize'=>false], // 'pluralize'=>false for working at CURL

            ),


        ],

Create New file Model common/models/Api.php


<?php


namespace common\models;


use yii\db\ActiveRecord;

use yii\web\IdentityInterface;


/*

    Model REST API

    by Adi Apriyanto

    13-6-2017

*/




class Api extends ActiveRecord implements IdentityInterface

{

    public static function tableName()

    {

        return 'user_rest_api';

    }


    public function validatePassword($username, $password)

    {

        // Use default validating or define yourself 

        return md5($password) === self :: findByUsername($username)['password'];

    }

    public static function findByUsername($username)

    {

        return static::findOne(['username' => $username]);

    }


    public static function findIdentity($id)

    {

        return static::findOne($id);

    }


    public static function findIdentityByAccessToken($token, $type = null)

    {

        return static::findOne(['token' => $token]);

    }


    public function getId()

    {

        return $this->id;

    }


    public function getAuthKey()

    {

        return $this->authKey;

    }


    public function validateAuthKey($authKey)

    {

        return $this->authKey === $authKey;

    }

}

Create new file Controller frontend/controller/ApiController.php


<?php


namespace frontend\controllers;


use yii\rest\ActiveController;

use yii\filters\auth\HttpBasicAuth;

use common\models\Api;


/*

    Controller REST API

    by Adi Apriyanto

    13-6-2017

*/


class ApiController extends ActiveController

{

    public $modelClass = 'frontend\models\UserRestApi'; // Example Model Table user_rest_api or define yourself


	public function behaviors()

	{

		$behaviors = parent::behaviors();

		$behaviors['authenticator'] = [

			'class' => HttpBasicAuth::className(),

			'auth' => function ($username, $password) {

				$user = Api::findByUsername($username);

				if ($user && $user->validatePassword($username, $password)) {

					return $user;

				}

			}

		];

		return $behaviors;

	}


}

Test your Api

All Data

[font="Courier New"]curl -i -H "Accept:application/json" "htpp://localhost/website/frontend/web/api" -u demo:demo[/font]

View by id

[font="Courier New"]curl -i -H "Accept:application/json" "htpp://localhost/website/frontend/web/api/view/1" -u demo:demo[/font]

Create

[font=“Courier New”]curl -i -H “Accept:application/json” -X POST “htpp://localhost/website/frontend/web/api/create” -u demo:demo -d ‘username=test&password=098f6bcd4621d373cade4e832627b4f6&token=54321’[/font]

Update

[font=“Courier New”]curl -i -H “Accept:application/json” -X PUT “htpp://localhost/website/frontend/web/api/update?id=2” -u demo:demo -d ‘username=test_aja&password=test_aja&token=test_aja’[/font]

Delete

[font="Courier New"]curl -i -H "Accept:application/json" -X DELETE "htpp://localhost/website/frontend/web/api/delete?id=2" -u demo:demo[/font]