rest - 为 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 未经授权
解决方案
使用amHttpAuthenticated
方法:https ://codeception.com/docs/modules/REST#amHttpAuthenticated
$I->amHttpAuthenticated('username', 'password');
推荐阅读
- c# - 如何正确加载重集?
- java - Rest-Api 在 Spring Boot 中调用其他 Rest-Api 不工作(多部分文件)
- javascript - 除了使用位置:绝对,然后使用位置:...之外,还有其他方法可以使工作成为滑块
- c# - 刷新令牌后创建订阅
- python - 结合编码器和解码器模型
- javascript - 使用 Vue.js 获取所有选中复选框的列表
- python - Django 1.11 python3 语法错误:迁移 manage.py 时扫描 __init__ 中的字符串文字时出现 EOL
- java - Java 导入 /lib 文件
- java - 递归地用字符串中的 3.14 替换 pi(无循环)
- docker - Docker Alpine 错误:可能未定义的宏:AC_PROG_LIBTOOL