REST API无需身份验证方法即可运行。现在,我想通过移动应用程序对API请求进行HTTP基本身份验证来验证REST API。我试过yii2指南,但它对我没用。
基本上移动用户需要使用用户名&密码,如果用户名和密码正确,则用户需要登录,并且需要使用令牌验证进一步的API请求。
当我调试findIdentityByAccessToken()函数时,$ token等于用户名。 Postman扩展用于检查HTTP Basic请求。 用户表中的access_token字段为空。我需要手动保存吗? 如何将access_token作为响应返回?
是否有任何理由同时使用所有三种方法(HttpBasicAuth,HttpBearerAuth,QueryParamAuth),为什么?怎么样?
我的应用程序文件夹结构如下所示。
api
-config
-modules
--v1
---controllers
---models
-runtime
-tests
-web
backend
common
console
environments
frontend
API \模块\ V1 \ Module.php
namespace api\modules\v1;
class Module extends \yii\base\Module
{
public $controllerNamespace = 'api\modules\v1\controllers';
public function init()
{
parent::init();
\Yii::$app->user->enableSession = false;
}
}
API \模块\ V1 \控制器\ CountryController.php
namespace api\modules\v1\controllers;
use Yii;
use yii\rest\ActiveController;
use common\models\LoginForm;
use common\models\User;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBasicAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;
class CountryController extends ActiveController
{
public $modelClass = 'api\modules\v1\models\Country';
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
//'class' => CompositeAuth::className(),
// 'authMethods' => [
// HttpBasicAuth::className(),
// HttpBearerAuth::className(),
// QueryParamAuth::className(),
// ],
];
return $behaviors;
}
}
常见\模型\ user.php的
namespace common\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
public static function tableName()
{
return '{{%user}}';
}
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
];
}
public static function findIdentity($id)
{
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
}
}
用户表
id
username
auth_key
password_hash
password_reset_token
email
status
created_at
access_token
迁移用户表后添加了access_token
答案 0 :(得分:15)
您需要在保存用户之前设置令牌。在用户模型中使用此
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if ($this->isNewRecord) {
$this->auth_key = Yii::$app->getSecurity()->generateRandomString();
}
return true;
}
return false;
}
现在每个用户都有一个auth_key
返回auth_key,你需要在UserController中添加actionLogin
public function actionLogin()
{
$post = Yii::$app->request->post();
$model = User::findOne(["email" => $post["email"]]);
if (empty($model)) {
throw new \yii\web\NotFoundHttpException('User not found');
}
if ($model->validatePassword($post["password"])) {
$model->last_login = Yii::$app->formatter->asTimestamp(date_create());
$model->save(false);
return $model; //return whole user model including auth_key or you can just return $model["auth_key"];
} else {
throw new \yii\web\ForbiddenHttpException();
}
}
之后,在每个API请求中,您都会在标头中发送auth_key,而不是发送用户名和密码
$ curl -H "Authorization: Basic bd9615e2871c56dddd8b88b576f131f51c20f3bc" API_URL
检查auth_key是否有效,在UserController行为中定义'authenticator'。 (不要忘记从身份验证中排除'create','login','resetpassword')
public function behaviors()
{
return ArrayHelper::merge(
parent::behaviors(), [
'authenticator' => [
'class' => CompositeAuth::className(),
'except' => ['create', 'login', 'resetpassword'],
'authMethods' => [
HttpBasicAuth::className(),
HttpBearerAuth::className(),
QueryParamAuth::className(),
],
],
]
);
}