php - 邮递员工作时,对 JWT API 的 Guzzle POST 请求未经授权
问题描述
在 Postman 工作时,对 JWT API 的 Guzzle POST 请求未经授权。这是代码:
public function __construct()
{
$this->client = new Client();
$this->connect();
}
public function connect()
{
$loginResult = $this->client->request('POST', config('api.base_uri') .'/auth/login', [
'form_params' => [
'email' => config('api.login'),
'password' => config('api.password'),
]
]);
dd(json_decode($loginResult->getBody()));
}
运行此代码时,我得到 401 Unauthorized。凭据正确传递。同时在 Postman 中,它运行良好:
请告诉我我做错了什么。谢谢!
更新 以下是此请求在 API 端命中的控制器和函数:
class AuthController extends Controller
{
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
public function login(Request $request)
{
$credentials = $request->only(['email', 'password']);
if (!$token = auth('api')->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized '.$credentials['email']], 401);
}
return $this->respondWithToken($token);
}
...
用户确实存在,因为它在 Postman 中工作
更新 2 我简化了代码,发现这是错误的:
Route::get('/guzzle', function () {
$client = new Client([
'headers' => [
'Accept' => 'application/json'
]]);
$loginResult =
$client->request('POST', config('pics.base_uri') .'/auth/login', [
'form_params' => [
'email' => '****@****.com',
'password' => '*****',
]
]);
dd(json_decode($loginResult->getBody()));
});
它不起作用 - 得到同样的错误
解决方案
好的......经过几个小时和Kyslik的善意帮助,我找到了这个问题的线索。实际上帮助我的是调试和查找我得到的错误。最终我发现了以下帖子(https://github.com/guzzle/guzzle/issues/1413#issuecomment-222031665),其中陈述了一种奇怪的事情:
如果使用相同的 PHP 实例从 Guzzle 发送请求并响应该请求,Guzzle 将根本无法工作
我把所有东西都搬到了主机上,它就像一个魅力。希望这将有助于将来的人。
感谢所有参与寻找解决方案的人,当然还有Kyslik!
推荐阅读
- python - 在 Python 3 中使用 zip_longest 时,for 循环不插入换行符
- docker - 如何在 Ubuntu 14.04 Dockerfile 中更新我的根证书?
- python - vendor_prefix selenium webdriver
- haskell - 什么模式适合在 SBV 公式中表示 Null 值
- c# - 不同的静态只读属性实现(与字段)在 C# 中的行为如何?
- reactjs - 如何在 MUI v5 中使用 react-router-dom 链接键入按钮
- bash - 当在 git repo 中更改 master 时,有没有办法在 Linux 机器上运行脚本?
- protocol-buffers - 如何在芭蕾舞演员中为客户端服务器创建协议缓冲区?
- nestjs - 类验证器不验证数据
- javascript - JavaScript:JSON 循环通过相似的键名