且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Yii 2 RESTful API使用HTTP Basic进行身份验证(Yii 2高级模板)

更新时间:2023-09-20 21:37:34

在保存用户之前,您需要设置令牌.在用户模型中使用

You need to set the token before saving the user. in the User model use this

public function beforeSave($insert)
{
    if (parent::beforeSave($insert)) {
        if ($this->isNewRecord) {
            $this->auth_key = Yii::$app->getSecurity()->generateRandomString();
        }
        return true;
    }
    return false;
}

现在您为每个用户拥有一个auth_key

now you have an auth_key for each user

要返回auth_key,您需要在UserController中添加actionLogin

to return the auth_key you need to add actionLogin in the UserController

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而不是发送用户名和密码

after that, in each API request you send the auth_key in the header instead of sending username and password

$ curl -H "Authorization: Basic bd9615e2871c56dddd8b88b576f131f51c20f3bc" API_URL

要检查auth_key是否有效,请在UserController行为中定义"authenticator". (不要忘记从身份验证中排除创建",登录",重置密码")

to check if the auth_key is valid, define 'authenticator' in the UserController behaviors. (don't forget to to exclude 'create', 'login', 'resetpassword' from the authentication)

public function behaviors()
{
    return ArrayHelper::merge(
        parent::behaviors(), [
            'authenticator' => [
                'class' => CompositeAuth::className(),
                'except' => ['create', 'login', 'resetpassword'],
                'authMethods' => [
                    HttpBasicAuth::className(),
                    HttpBearerAuth::className(),
                    QueryParamAuth::className(),
                ],
            ],
        ]
    );
}