带token的登录+注册:接口开发

举报
陈业贵 发表于 2021/12/10 10:36:58 2021/12/10
【摘要】 简单的接口开发

第一步:
注册:核心代码:

/*注册*/
      /* $request = \Yii::$app->request;
        $username = $request->post('username');
        $password = $request->post('password');
        \Yii::$app->db->createCommand()->insert('user', [
            'username' => $username,
            'password' => $password,
        ])->execute();*/

postman下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/74a3bd63d8794c59a4dfe121da2cb1ae.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA6LS15ZOl55qE57yW56iL5LmL6LevKOmZiOS4mui0tSk=,size_20,color_FFFFFF,t_70,g_se,x_

mysql结构:(重点:id自增)
在这里插入图片描述

第二步:
在common/model/下里面新建一张表(User.php):复制粘贴

<?php
namespace common\models;

class User extends /*\yii\base\Object*/ \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
    /*public $id;
    public $username;
    public $password;
    public $authKey;
    public $accessToken;

    private static $users = [
        '100' => [
            'id' => '100',
            'username' => 'admin',
            'password' => 'admin',
            'authKey' => 'test100key',
            'accessToken' => '100-token',
        ],
        '101' => [
            'id' => '101',
            'username' => 'demo',
            'password' => 'demo',
            'authKey' => 'test101key',
            'accessToken' => '101-token',
        ],
    ];
    */

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password'], 'required'],
            [['username'], 'string', 'max' => 50],
            [['password'], 'string', 'max' => 32],
            [['authKey'], 'string', 'max' => 100],
            [['accessToken'], 'string', 'max' => 100],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'authKey' => 'AuthKey',
            'accessToken' => 'AccessToken',
        ];
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne($id);
        //return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
        /*foreach (self::$users as $user) {
            if ($user['accessToken'] === $token) {
                return new static($user);
            }
        }

        return null;*/
    }

    /**
     * Finds user by username
     *
     * @param  string      $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        $user = User::find()
            ->where(['username' => $username])
            ->asArray()
            ->one();

        if($user){
            return new static($user);
        }

        return null;
        /*foreach (self::$users as $user) {
            if (strcasecmp($user['username'], $username) === 0) {
                return new static($user);
            }
        }

        return null;*/
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->authKey;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->authKey === $authKey;
    }

    /**
     * Validates password
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return $this->password === $password;
    }
    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
        $this->generateAuthKey();
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Generates new token for email verification
     */
    public function generateEmailVerificationToken()
    {
        $this->verification_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }
}

token是什么?
在这里插入图片描述
第三步:第一次登录的时候生成token:然后我们可以拿着这个token去登录,不需要用户名+密码了.这相当于一个识别吧.
在这里插入图片描述

生成token的核心代码(并把token插入到数据库中)。

$request = \Yii::$app->request;
        $username = $request->post('username');
        $password = $request->post('password');

        //echo $authKey;
        $id = \Yii::$app->db->createCommand('SELECT id FROM user WHERE username=:username and password=:password')
            ->bindValue(':username', $username)
            ->bindValue(':password', $password)
            ->queryOne();
        if($id) {
            $authKey=\Yii::$app->security->generateRandomString();
            \Yii::$app->db->createCommand()->update("{{%user}}", [
                "authKey" => $authKey
            ], ['id' => $id])->execute();
            return $this->json("token=" . $authKey);
        }

第四步:带token的登录:(数据库中的token与输入的token保持一致就可以登录了),并显示登录的是谁???
核心代码:

 $request = \Yii::$app->request;
        $token = $request->post("token");
        $username = \Yii::$app->db->createCommand("SELECT username FROM user WHERE authKey=:token")
            ->bindValue(':token', $token)
            ->queryOne();
        if($username)
        {
            return $this->json($username,"使用token登录成功");
        }

在这里插入图片描述

【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。