eluhr/yii2-user-access-token

用户访问令牌Yii2

2.0.1 2023-01-24 13:59 UTC

This package is auto-updated.

Last update: 2024-09-24 17:24:12 UTC


README

此扩展提供了一种简单的方法,通过令牌进行用户认证。它易于扩展,可以与任何用户模型一起使用。

安装

composer require eluhr/yii2-user-access-token

配置

在您的控制台部分中,将以下内容添加到您的配置文件中

<?php
return [
    'controllerMap' => [
        'migrate' => [
            'migrationPath' => [
                '@vendor/eluhr/yii2-user-access-token/src/migrations'
            ]
        ]
    ]
]

示例用法

在您的用户模型中,您可以这样做

<?php

namespace app\models;

use eluhr\userAccessToken\models\Token;
use yii\base\NotSupportedException;
use yii\filters\auth\QueryParamAuth;
use yii\web\IdentityInterface;

class User extends yii\db\ActiveRecord implements IdentityInterface
{
    /**
     * @param $token
     * @param string $type
     *
     * @throws NotSupportedException
     * @return IdentityInterface|null
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        if ($type === QueryParamAuth::class) {
            $token = Token::findValidToken($token); // Change this to your token model if needed
            if ($token instanceof Token) {
                return $token->user;
            }
            return null;
        }

        return parent::findIdentityByAccessToken($token, $type);
    }
}

在您的控制器中

<?php

namespace app\controllers;

use yii\filters\AccessControl;
use yii\filters\auth\QueryParamAuth;
use yii\web\Controller;

class ExampleController extends Controller
{

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => QueryParamAuth::class
        ];
        $behaviors['access'] = [
            'class' => AccessControl::class,
            'rules' => [
                [
                    'actions' => ['index'],
                    'allow' => true,
                    'roles' => ['@']
                ]
            ]
        ];
        return $behaviors;
    }

    public function actionIndex()
    {
        return 'Hello World';
    }

}