首页 > 解决方案 > API with bearer and query params options

问题描述

I'm trying to get an API validation going. Below is my behavior

public function behaviors()
{
    return ArrayHelper::merge(parent::behaviors(), [
        'authenticator' => [
            'class' => CompositeAuth::class,
            'authMethods' => [
                ['class' => HttpBearerAuth::class],
                ['class' => QueryParamAuth::class, 'tokenParam' => 'admin-token'],
            ],
        ],
        'corsFilter' => [
            'class' => Cors::class,
        ],
        'access' => [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'ips' => Yii::$app->params['allowedIPs'], //Fill in the allowed IPs here
                    'allow' => true,
                ],
                [
                    'ips' => Yii::$app->params['adminIPs'], //Fill in the allowed IPs here
                    'allow' => true,
                    'matchCallback' => function ($rule, $action) {
                        return (!empty($_GET['admin-token']) && $_GET['admin-token'] === Yii::$app->params['adminApiToken']);
                    }
                ],
            ],
        ]
    ]);

the bearer method works and checks for matching access token and ip. but for admin matching IP and admin-token it fails and i get this error

stdClass#1
(
    [success] => false
    [data] => stdClass#2
    (
        [name] => 'Unauthorized'
        [message] => 'Your request was made with invalid credentials.'
        [code] => 0
        [status] => 401
    )
) 

how do i get validation credential using admin-token for admin only?

标签: phpyiiyii2

解决方案


推荐阅读