• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Yii2-Resultful-Api-认证

php 搞代码 4年前 (2022-02-28) 43次浏览 已收录 0个评论
文章目录[隐藏]

Yii2 Resultful Api 认证

​ 应用access token 作为用户登录认证信息

1. 批改认证

  • main.php

    <code class="php">/*** 认证类 ***/
    'user' => [
        'identityClass' => 'common\models\backend\Admin',
        'enableAutoLogin' => true,
        'enableSession' => FALSE, // 敞开session
        // 'identityCookie' => ['name' => '_identity-api', 'httpOnly' => true],
    ],
    // 'session' => [
    //     'name' => 'advanced-api',
    // ],

2. 获取access token

  • 认证类Admin

    <code class="php">namespace common\models\backend;
    
    use Yii;
    use yii\web\IdentityInterface;
    
    /**
     * This is the model class for table "admin".
     *
     * @property int    $id                   ID
     * @property string $username             用户名
     * @property string $realname             姓名
     * @property string $email                电子邮箱
     * @property int    $status               状态
     * @property string $password_hash        明码
     * @property string $auth_key             受权key
     * @property string $password_reset_token 明码重置token
     * @property string $access_token         拜访token
     * @property int    $expire_at            过期工夫
     * @property int    $logged_at            登入工夫
     * @property int    $created_at           创立工夫
     * @property int    $updated_at           最初批改工夫
     */
    class Admin extends \yii\db\ActiveRecord implements IdentityInterface
    {
        /**
         * {@inheritdoc}
         */
        public static function tableName()
        {
            return 'admin';
        }
    
        /**
         * {@inheritdoc}
         */
        public function rules()
        {
            return [
                [['id', 'email', 'password_hash', 'auth_key'], 'required'],
                [['id', 'status', 'expire_at', 'logged_at', 'created_at', 'updated_at'], 'integer'],
                [['username'], 'string', 'max' => 32],
                [['realname', 'email', 'password_hash', 'auth_key', 'password_reset_token', 'access_token'], 'string',
                 'max' => 255],
            ];
        }
    
        /**
         * {@inheritdoc}
         */
        public function attributeLabels()
        {
            return [
                'id'                   => 'ID',
                'username'             => '用户名',
                'realname'             => '姓名',
                'email'                => '电子邮箱',
                'status'               => '状态',
                'password_hash'        => '明码',
                'auth_key'             => '受权key',
                'password_reset_token' => '明码重置token',
                'access_token'         => '拜访token',
                'expire_at'            => '过期工夫',
                'logged_at'            => '登入工夫',
                'created_at'           => '创立工夫',
                'updated_at'           => '最初批改工夫',
            ];
        }
    
    
        public static function findIdentity($id)
        {
            // TODO: Implement findIdentity() method.
        }
    
    
        public static function findIdentityByAccessToken($token, $type = NULL)
        {
            // TODO: Implement findIdentityByAccessToken() method.
        }
    
    
        public function getId()
        {
            // TODO: Implement getId() method.
        }
    
    
        public function getAuthKey()
        {
            // TODO: Implement getAuthKey() method.
        }
    
    
        public function validateAuthKey($authKey)
        {
            // TODO: Implement validateAuthKey() method.
        }
    
    
        /**
         * 应用用户名查找用户
         *
         * @param $username
         * @return \common\models\backend\Admin|null
         */
        public static function findByUsername($username)
        {
            return static::findOne(['username' => $username]);
        }
    
        /**
         * 验证明码
         *
         * @param string $password password to validate
         * @return bool if password provided is valid for current user
         */
        public function validatePassword($password)
        {
            return Yii::$app->security->validatePassword($password, $this->password_hash);
        }
    
        /**
         * 生成access token
         *
         * @return string
         * @throws \yii\base\Exception
         */
        public function generateAccessToken()
        {
            $this->access_token = Yii::$app->security->generateRandomString();
            return $this->access_token;
        }
    }
    
  • 控制器文件

    <code class="php">namespace api\modules\backend\controllers;
    
    use api\models\backend\AdminLoginForm;
    
    class AdminController extends \yii\rest\ActiveController
    {
        public $modelClass = "common\models\backend\Admin";
    
        /**
         * 用户登录
         *
         * @return \api\models\backend\AdminLoginForm|array
         * @throws \yii\base\Exception
         */
        public function actionLogin()
        {
            $model = new AdminLoginForm();
    
            $model->username = $_POST['username'];
            $model->password = $_POST['password'];
    
            if ($model->login()) {
                return ['access_token' => $model->login()];
            } else {
                $model->validate();
                return $model;
            }
        }
    }
    
  • 后盾用到的登录表单模型类

    <code class="php">namespace api\models\backend;
    
    use common\models\backend\Admin;
    use yii\base\Model;
    
    /**
     * 登录表单
     */
    class AdminLoginForm extends Model
    {
        public $username;
        public $password;
    
        /**
         * @var Admin
         */
        private $_user;
    
    
        /**
         * {@inheritdoc}
         */
        public function rules()
        {
            return [
                // username and password are both required
                [['username', 'password'], 'required'],
                // password is validated by validatePassword()
                ['password', 'validatePassword'],
            ];
        }
    
        /**
         * @param $attribute
         * @param $params
         */
        public function validatePassword($attribute, $params)
        {
            if (!$this->hasErrors()) {
                $user = $this->getUser();
                if (!$user || !$user->validatePassword($this->password)) {
                    $this->addError($attribute, 'Incorrect username or password.');
                }
            }
        }
    
        /**
         * @return string|bool
         * @throws \yii\base\Exception
         */
        public function login()
        {
            if ($this->validate()) {
                $accessToken = $this->_user->generateAccessToken();
                $this->_user->save();
                return $accessToken;
            }
            return FALSE;
        }
    
        /**
         * 查找用户
         *
         * @return Admin|null
         */
        protected function getUser()
        {
            if ($this->_user === NULL) {
                $this->_user = Admin::findByUsername($this->username);
            }
            return $this->_user;
        }
    }
    

3. 认证access token

  • 批改每个controller

    <code class="php">/**
         * 认证用户 access token
         * @return array
         */
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(),[
            'authenticatior' => QueryParamAuth::className()
        ]);
    }
  • 实现Admin类里的findIdentityByAccessToken 办法

    <code class="php">/**
         * 通过access token 获取用户信息
         * @param mixed $token
         * @param null  $type
         * @return \common\models\backend\Admin|\yii\web\IdentityInterface|null
         */
    public static function findIdentityByAccessToken($token, $type = NULL)
    {
        return static::findOne(['access_token'=>$token]);
    }

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Yii2-Resultful-Api-认证
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址