PHP code example of rob006 / yii2-simple-auth

1. Go to this page and download the library: Download rob006/yii2-simple-auth library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rob006 / yii2-simple-auth example snippets


return [
	...
	'params' => [
		...
		'simpleauth' => [
			'secret' => 'mysecretkey',
		],
	],
];

use rob006\simpleauth\Authenticator;

$ch = curl_init();
$url = 'http://api.example.com/user/list/?ids=1,2,3,4';
$url .= '&' . Authenticator::PARAM_NAME . '=' . Authenticator::generateAuthToken($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);

use rob006\simpleauth\Authenticator;

$ch = curl_init();
$url = 'http://api.example.com/user/list/?ids=1,2,3,4';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
	Authenticator::HEADER_NAME . ': ' . Authenticator::generateAuthToken($url),
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);

use rob006\simpleauth\ActionFilter;

class MyController extends \yii\web\Controller {

	public function behaviors() {
		return [
			...
			'simpleauth' => [
				'class' => ActionFilter::className(),
			],
		];
	}

	...
}

use rob006\simpleauth\ActionFilter;
use rob006\simpleauth\Authenticator;

class MyController extends \yii\web\Controller {

	public function behaviors() {
		return [
			...
			'simpleauth' => [
				'class' => ActionFilter::className(),
				// allow authentication only by header
				'allowedMethods' => [
					Authenticator::METHOD_HEADER,
				],
				// set token timeout to 1 hour (by default it is 5 minutes)
				'tokenDuration' => 3600,
				// override default header used for authentication
				'headerName' => 'X-My-Custom-Header',
				// override params names used for send authentication token
				'postParamName' => 'my_custom_token_param_name',
				'getParamName' => 'my_custom_token_param_name',
				// custom secret used for validate authentication
				'secret' => 'my-custom-secret-key',
			],
		];
	}

	...
}