Hello
I want to implement a api rest, and for the authentication i want to use a token. But the token can be used for users authenticated or not authenticated.
When i follow the manual (RESTful Web Services: Authentication | The Definitive Guide to Yii 2.0 | Yii PHP Framework), and implement the behaviour ‘authenticator’, is necessary to implement the method findIdentityByAccessToken…but this method is called automattically in the method login of the class User of webvimark. If the user can be a guest, i cannot implement this method…
how an i resolve this? in resume, i just want that a person with the url and the correct token can acces or not the api resource.
You can easily implement your own custom authentication for REST in any controller, even without introducing additional class(es). Just disable CSRF validation, disable opening session and define callback functions matchCallback and optionally denyCallback - example:
namespace app\modules\api\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\HttpException;
class V1Controller extends Controller
{
// disable CSRF since we have disabled session for REST - validation would always fail
public $enableCsrfValidation = false;
public function init()
{
// chain properly initialization
parent::init();
// REST does not use session, each request is disconnected and must be validated
Yii::$app->user->enableSession = false;
}
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
//'except' => ['action-without-access-control'],
'rules' => [
[
'actions' => ['my-authorized-action'],
'allow' => true,
'matchCallback' => function($rule, $action){
if (!empty($_GET['access-token']) && ($token = htmlspecialchars($_GET['access-token']))) {
if(Yii::$app->user->loginByAccessToken($token)){
// handle existing users ...
}else{
// handle non-existing users ...
// make sure token is valid, e.g. contains some encrypted information
// otherwise how would you distinguish invalid token and non-authenticated user?
}
return true; // return success = found token
}
return false; // return false = access denied, token not found
},
],
],
'denyCallback' => function($rule, $action){
throw new HttpException(403, 'Unauthorized access!');
}
],
];
}
}