且构网

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

Yii2 REST 简化 BasicAuth

更新时间:2023-09-20 21:28:28

让我们观察并尝试理解yii"方式的 REST 基本身份验证.

Let's watch and try to understand "yii" way basic auth for REST.

第一.当您向 REST 控制器添加行为时,您将启用基本身份验证:

1st. When you adding behavior to your REST controller, you enabling basic auth:

$behaviors['authenticator'] = [
    'class' => HttpBasicAuth::className(),
  ];

正如你所做的那样.这是什么意思?这意味着您的应用程序将解析您的授权标头.它看起来像:

As you did. What does it mean? It means that your application will parse your authorization header. It looks like:

Authorization : Basic base64(user:password)

这是 yii2 的一个技巧.如果您更仔细地查看代码,您会看到 yii 使用了来自用户字段的 access_token,因此您的标题应该如下所示:

Here is a trick for yii2. If you look at code more carefully, you will see that yii uses access_token from user field, so your header should look like:

Authorization : Basic base64(access_token:)

如果你想改变这个行为,你可以自己解析这个头:

You can parse this header by your own, if you want to change this behavior:

$behaviors['authenticator'] = [
            'class' => HttpBasicAuth::className(),
            'auth' => [$this, 'auth']
        ];
....
public function auth($username, $password)
    {
        return \app\models\User::findOne(['login' => $username, 'password' => $password]);
    }

要做的第二件事.您必须从 identityInterface 实现 findIdentityByAccessToken() 函数.为什么您的 IDE 会抱怨?

2nd thing to do. You must implement findIdentityByAccessToken() function from identityInterface. Why your IDE complaining?

class User extends ActiveRecord implements IdentityInterface

您的用户类声明应如下所示.

Here's how your user class declaration should look.

来自您的实施和结构:

public static function findIdentityByAccessToken($token, $type = null)
   {
     return static::findOne(['access_token' => $token]);
   }

您没有返回实现身份接口的类的对象.

you not returning object of class which implements identity interface.

如何正确制作?将列 access_token 添加到您的用户表中,并返回您的用户模型(您可以在此处查看它的外观 - https://github.com/yiisoft/yii2-app-advanced/blob/master/common/models/User.php)如果您这样做 - 默认代码将与您的 findIdentityByAccessToken() 实现一起使用.

How to make it properly? Add column access_token to your users table, and return back your user model (you can look how it must look here - https://github.com/yiisoft/yii2-app-advanced/blob/master/common/models/User.php) If you do this - default code will work with your findIdentityByAccessToken() implementation.

如果您不想向用户表中添加字段 - 使用 user_id,access_token 字段创建一个新字段.那么你的实现应该是这样的:

If you don't want to add field to users table - make new one with user_id,access_token fields. Then your implementation should look like:

public static function findIdentityByAccessToken($token, $type = null)
   {
     $apiUser = ApiAccess::find()
        ->where(['access_token' => $token])
        ->one();
     return static::findOne(['id' => $apiUser->user_id, 'status' => self::STATUS_ACTIVE]);
   }

希望我能解答你所有的问题.

Hope i could cover all of your questions.