Yii Framework Forum: Yii2 Rest Api with Username and Password - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Yii2 Rest Api with Username and Password Yii2 Rest Api with Username and Password

#1 User is offline   adyoi 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 2
  • Joined: 13-June 17

Posted 13 June 2017 - 11:15 AM

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')



username : 'demo'
password : 'fe01ce2a7fbac8fafaed7c982a04e229' (encrypt to md5 or define in model)
token : '12345' (Free Random Value)


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

curl -i -H "Accept:application/json" "htpp://localhost/website/frontend/web/api" -u demo:demo

View by id

curl -i -H "Accept:application/json" "htpp://localhost/website/frontend/web/api/view/1" -u demo:demo

Create

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'

Update

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'

Delete

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

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users