php - Postman 工作时,Guzzle POST 请求 JWT API 未经授权

标签 php laravel jwt postman guzzle

在 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 中它运行得很好: While in Postman it is working perfectly

请告诉我我做错了什么。 谢谢!

更新 以下是该请求在 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/

相关文章:

php - 使用 mamp 在本地测试电子邮件

php - 如何调试似乎没有运行的 PHP CRON 脚本?

php - Laravel 5 本地化 : exclude/public/directory

php - laravel morphTo 如何使用自定义列?

php - 获取具有相同 id 的多个表的信息

php - 在 Woocommerce 中添加到购物车之前用于更改产品价格的附加自定义按钮

php - 错误 $HTTP_RAW_POST_DATA 已弃用,请使用 php ://input stream instead. "

java - 如何使用 RSA256 算法生成 JWT 签名?

javascript - jwt.verify() 的 Node.js 回调

security - JWT token SSO 流程