在 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 端命中的 Controller 和函数:
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)其中陈述了一些奇怪的事情:
Guzzle won't work at all if the same instance of PHP is used to send the Request from Guzzle, and to respond that request
我把所有东西都转移到了托管上,它很有魅力。希望这对将来的人有所帮助。
感谢所有参与寻找解决方案的人,当然还有 Kyslik !
关于php - Postman 工作时,Guzzle POST 请求 JWT API 未经授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50879529/