在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"}');
}
在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未经授权
答案 0 :(得分:1)
使用amHttpAuthenticated
方法:https://codeception.com/docs/modules/REST#amHttpAuthenticated
$I->amHttpAuthenticated('username', 'password');