首页 > 解决方案 > 邮递员工作时,对 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 中,它运行良好: 在 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()));
});

它不起作用 - 得到同样的错误

标签: phplaraveljwtpostmanguzzle

解决方案


好的......经过几个小时和Kyslik的善意帮助,我找到了这个问题的线索。实际上帮助我的是调试和查找我得到的错误。最终我发现了以下帖子(https://github.com/guzzle/guzzle/issues/1413#issuecomment-222031665),其中陈述了一种奇怪的事情:

如果使用相同的 PHP 实例从 Guzzle 发送请求并响应该请求,Guzzle 将根本无法工作

我把所有东西都搬到了主机上,它就像一个魅力。希望这将有助于将来的人。

感谢所有参与寻找解决方案的人,当然还有Kyslik


推荐阅读