首页 > 解决方案 > 为 yii2 运行 codecept REST 如何获取 $_SERVER['PHP_AUTH_USER']?

问题描述

在 api.suite.yml 中配置模块 class_name: ApiTester modules: enabled: - REST: url: http://xxxx depends: Yii2 - \backend\tests\Helper\Api config: - Yii2

类 UserLoginCest

public function tryToTest(ApiTester $I)
{
    $I->haveHttpHeader('Authorization', 'Basic Og==');
    $I->sendPOST('/admin/user/login', ['username' => 'wen', 'password' => '123456']);
    $I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK); // 200
    $I->seeResponseIsJson();
    $I->seeResponseContains('{"result":"ok"}');
}

在用户控制器 $behaviors

$behaviors['authenticator'] = [
            'class' => CompositeAuth::class,
            'authMethods' => [
                [
                    'class' => HttpBasicAuth::class,
                    'auth' => function ($username, $password) {
                        $request = Yii::$app->request;
                        $username = $username ?: $request->post('username');
                        $password = $password ?: $request->post('password');
                        if (!$user = User::findByUsername($username)) {
                            return null;
                        }
                        if (!$user->validatePassword($password)) {
                            return null;
                        }
                        if ($user->login()) {
                            return $user;
                        }
                        return null;
                    }
                ],
            ]
        ];

在 Yii2 HttpBasicAuth

$username = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : null;
    $password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : null;

var_dump($_SERVER) 未设置 $_SERVER['PHP_AUTH_USER'] 响应 401 未经授权

标签: restyii2codeception

解决方案


使用amHttpAuthenticated方法:https ://codeception.com/docs/modules/REST#amHttpAuthenticated

$I->amHttpAuthenticated('username', 'password');

推荐阅读