RESTful with authentication
polinwei opened this issue · comments
Hi Sir:
Is possible to setup a authentication for RESTful?
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:
- Implement the findIdentityByAccessToken() in the User model
yii2-advanced-start/modules/users/models/User.php
Lines 302 to 305 in 943ebab
- Configure authentication method
Done! Checking:
http://yii2-advanced-start.loc/api/users // All users received
We put the authentication on the action index
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:
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.
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:
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:
Login by login and password or by token
Documentation: http://www.yiiframework.com/doc-2.0/yii-filters-auth-compositeauth.html
Excellent !! Thanks