运行yii2的REST代码如何获取$ _SERVER ['PHP_AUTH_USER']?

问题描述 投票:0回答:1

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

class 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"}');
}

在UserController中为$ 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未经授权

rest yii2 codeception
1个回答
2
投票

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

$I->amHttpAuthenticated('username', 'password');
© www.soinside.com 2019 - 2024. All rights reserved.