Closed polinwei closed 6 years ago
Hi! Look in the documentation: http://www.yiiframework.com/doc-2.0/guide-rest-authentication.html
To implement authentication, you need to do the following steps:
Done! Checking:
http://yii2-advanced-start.loc/api/users // All users received
We put the authentication on the action index https://github.com/Dominus77/yii2-advanced-start/blob/a4387f066a4af68bf1139c4d9a63082ba5115359/modules/users/controllers/api/DefaultController.php#L31-L33 Checking
http://yii2-advanced-start.loc/api/users // Received status 401
Trying to authenticate
http://yii2-advanced-start.loc/api/users?auth_key=4GLpuUYaqFpoKQ9i8FiQaLxcWnkcdBo9 // All users received
auth_key field: https://github.com/Dominus77/yii2-advanced-start/blob/17172457fed1bfa6ce1ac8e0267d0a03aeee426e/modules/users/models/User.php#L22
Authorized User Key:
echo Yii::$app->user->identity->auth_key;
Hi Sir: Thanks!! Your explanation is so clear and simple. BTW whether I can to specify a specific user with its access token ?
Hi, thanks)
Thanks!! Your explanation is so clear and simple. BTW whether I can to specify a specific user with its access token ?
If you mean RBAC then yes, access control does not differ from the normal mode.
Or what do you mean?
The user's token can be displayed for example in its profile. https://github.com/Dominus77/yii2-advanced-start/blob/021f5be11aa2fa237db1e8da644622923964ab1d/modules/users/views/frontend/default/index/_profile.php#L41 Before using the API, the user must find out his / her token. This is generally a standard OAuth procedure.
Do it has the parameter $behaviors['authenticator']['userParam']
?
$behaviors['authenticator']['tokenParam'] = 'auth_key';
$behaviors['authenticator']['userParam'] = 'username';
then
http://yii2-advanced-start.loc/api/users?user=polin&auth_key=4GLpuUYaqFpoKQ9i8FiQaLxcWnkcdBo9
If you want to provide access by login and password, you can use: http://www.yiiframework.com/doc-2.0/yii-filters-auth-httpbasicauth.html
Just replace it: https://github.com/Dominus77/yii2-advanced-start/blob/a4387f066a4af68bf1139c4d9a63082ba5115359/modules/users/controllers/api/DefaultController.php#L31-L33 On this:
$behaviors['authenticator'] = [
'class' => \yii\filters\auth\HttpBasicAuth::className(),
'only' => ['update'],
'auth' => function ($username, $password) {
$user = \modules\users\models\api\User::find()->where(['username' => $username])->one();
if ($user->validatePassword($password)) {
return $user;
}
return null;
},
];
Multiple authentication methods: https://github.com/Dominus77/yii2-advanced-start/blob/eced50799d1dd6001cfb0809b07370b0d1c1260e/modules/users/controllers/api/DefaultController.php#L33-L55
Login by login and password or by token
Documentation: http://www.yiiframework.com/doc-2.0/yii-filters-auth-compositeauth.html
Excellent !! Thanks
Hi Sir:
Is possible to setup a authentication for RESTful?