框架中的RESTful api快速领悟(中):token认证

我们讲一下RESTful api中很重要的环节—token认证。本课程主要演示如何快速借助YII2配置出简单的token认证方法,并给出扩展的思路
1.创建一个用来作权限验证的表

CREATE TABLE `clients` (
  `client_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `client_appid` varchar(255) NOT NULL DEFAULT '',
  `client_appkey` varchar(255) NOT NULL DEFAULT '',
  `client_token` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`client_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;

然后需要创建一个Clients模型,以备后用:

<?php

namespace app\models;

use yii\db\ActiveRecord;

class Clients extends ActiveRecord
{
    //指定表名称
    static public function tableName()
    {
        return 'clients';
    }
}

2.授权认证
文档:http://www.yiichina.com/doc/guide/2.0/rest-authentication

<?php

namespace app\controllers;

use yii\filters\auth\QueryParamAuth;
use yii\rest\ActiveController;
use yii\web\Response;


class UserController extends ActiveController
{
    public $modelClass = 'app\models\Users';

    public function init()
    {
        parent::init();
        //关掉csrf
        $this->enableCsrfValidation = false;
        //关掉session
        \Yii::$app->user->enableSession = false;
    }

    public function behaviors()
    {
        $behaviors = parent::behaviors();

        //设置响应格式
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        //授权认证
        $behaviors['authenticator'] = [
            'class' => QueryParamAuth::className(), //我们使用的是QueryParamAuth
        ];

        return $behaviors;
    }
}

主要是initbehaviors那2句。

3.设置整个项目的验证
config/web.php

        'user' => [
//            'identityClass' => 'app\models\User',
//            'enableAutoLogin' => true,
            'identityClass' => 'app\models\Clients', //验证的时候调用这个类
        ],

4.完善Clients模型

<?php
<?php

namespace app\models;

use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

class Clients extends ActiveRecord implements identityInterface
{
    //指定表名称
    static public function tableName()
    {
        return 'clients';
    }

    /**
     * Finds an identity by the given ID.
     * @param string|integer $id the ID to be looked for
     * @return IdentityInterface the identity object that matches the given ID.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentity($id)
    {
        // TODO: Implement findIdentity() method.
    }

    /**
     * Finds an identity by the given token.
     * @param mixed $token the token to be looked for
     * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
     * @return IdentityInterface the identity object that matches the given token.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        // TODO: Implement findIdentityByAccessToken() method.
        return self::findOne(['client_token'=>$token]);
    }

    /**
     * Returns an ID that can uniquely identify a user identity.
     * @return string|integer an ID that uniquely identifies a user identity.
     */
    public function getId()
    {
        // TODO: Implement getId() method.
    }

    /**
     * Returns a key that can be used to check the validity of a given identity ID.
     *
     * The key should be unique for each individual user, and should be persistent
     * so that it can be used to check the validity of the user identity.
     *
     * The space of such keys should be big enough to defeat potential identity attacks.
     *
     * This is required if [[User::enableAutoLogin]] is enabled.
     * @return string a key that is used to check the validity of a given identity ID.
     * @see validateAuthKey()
     */
    public function getAuthKey()
    {
        // TODO: Implement getAuthKey() method.
    }

    /**
     * Validates the given auth key.
     *
     * This is required if [[User::enableAutoLogin]] is enabled.
     * @param string $authKey the given auth key
     * @return boolean whether the given auth key is valid.
     * @see getAuthKey()
     */
    public function validateAuthKey($authKey)
    {
        // TODO: Implement validateAuthKey() method.
    }
}

这个时候,我们再去访问:http://localhost/yiiserver/web/index.php/users 就会报错:

{"name":"Unauthorized","message":"Your request was made with invalid credentials.","code":0,"status":401,"type":"yii\\web\\UnauthorizedHttpException"}

没有访问权限了

5.带着access_token访问
http://localhost/yiiserver/web/index.php/users?access-token=abcabc
这样就可以正常访问了,access-token=abcabcabcabc就是我们clicents表存在的client_token的值。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值