Yii 2 RESTful API 使用 HTTP Basic 进行身份验证(Yii 2 高级模板) [英] Yii 2 RESTful API authenticate with HTTP Basic (Yii 2 advanced template)

查看:32
本文介绍了Yii 2 RESTful API 使用 HTTP Basic 进行身份验证(Yii 2 高级模板)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

REST API 在没有身份验证方法的情况下工作.现在我想通过移动应用程序对 API 请求进行 HTTP 基本身份验证来对 REST API 进行身份验证.我尝试使用 yii2 指南,但它对我不起作用.

REST API is working without authentication methods. Now i wanted to authenticate REST API with HTTP Basic authentication for API requests via mobile application. I tried with yii2 guide, but it didn't work for me.

基本上移动用户需要使用用户名登录密码,如果用户名和密码正确,用户需要登录,进一步的API请求需要使用token验证.

basically mobile user need to be login with username & password, if a username and password are correct, user need to be login and further API request need to be validate with token.

当我调试 findIdentityByAccessToken() 函数时,$token 等于用户名.用于检查 HTTP 基本请求的 Postman 扩展.用户表中的 access_token 字段为空.我需要手动保存吗?如何返回 access_token 作为响应?

when i debug findIdentityByAccessToken() function $token equal to username. Postman extension used for check HTTP Basic requests. access_token field in user table is empty. do i need to save it manually ? how to return access_token as a respond?

是否有任何理由同时使用所有三种方法(HttpBasicAuth、HttpBearerAuth、QueryParamAuth),为什么?如何?

is there any reason for all three methods(HttpBasicAuth, HttpBearerAuth, QueryParamAuth) at once, why? how?

我的应用程序文件夹结构如下所示.

my application folder structure looks like below.

api
-config
-modules
--v1
---controllers
---models
-runtime
-tests
-web

backend
common
console
environments
frontend

api\modules\v1\Module.php

api\modules\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\modules\v1\controllers\CountryController.php

api\modules\v1\controllers\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;
    }

}

common\models\User.php

common\models\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 是在迁移用户表后添加的

access_token was added after migrate user table

推荐答案

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

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(),
                ],
            ],
        ]
    );
}

这篇关于Yii 2 RESTful API 使用 HTTP Basic 进行身份验证(Yii 2 高级模板)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆