【问题标题】:Laravel Passport create fresh API token for Guzzle HTTP ClientLaravel Passport 为 Guzzle HTTP 客户端创建新的 API 令牌
【发布时间】:2019-02-20 04:30:10
【问题描述】:

显然,我能够使用 VueJs 的 Axios 和 jQuery 的 Ajax 通过 Javascript 使用我自己的 API,但同样无法使用 Guzzle HTTP 客户端。

如何将 CreateFreshApiToken 中间件与 Guzzle 一起使用。

Axios - 好的

axios.get('api/user').then(response => {
    console.log(response.data);
}).catch(error => {
    console.log(error.response.data);
});

Ajax - 好的

window.$.ajax({
    headers: {
        'Accept': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    type: 'GET',
    url: 'api/user',
    success: function (response) {
        console.log(response);
    },
    error: function (xhr) {
        console.error(xhr.responseText);
    }
});

Guzzle - 失败

try {
    $client = new Client([
        'base_uri' => 'http://localhost/passport-test/public/api/',
        'headers' => [
            'Accept' => 'application/json',
        ],
    ]);

    $api_response = $client->request('GET', 'user', ['debug' => true]);

    $user = json_decode($api_response->getBody(), true);

    return response()->json($user);
} catch (ConnectException $ex) {
    return response()->json(['code' => $ex->getCode(), 'message' => $ex->getMessage()]);
} catch (ClientException $ex) {
    return json_decode($ex->getResponse()->getBody(), true);
} catch (ServerException $ex) {
    return response()->json(['code' => $ex->getCode(), 'message' => $ex->getMessage()]);
}

【问题讨论】:

    标签: ajax laravel axios guzzle laravel-passport


    【解决方案1】:

    好吧,createFreshApiTokens 附加了一个 cookie 用于授权,但是当您使用 guzzle 时,您并没有从客户端(浏览器)发出请求,因此 cookie 不会附加到请求中!

    【讨论】:

    • 是的。但我试图弄清楚如何使用 guzzle 来达到同样的效果。现在我必须像使用任何其他第三方应用程序一样使用我自己的 API。
    • 你需要把token放在header中。 '授权' => '持有者' + $token.
    • 或在 cookie [laravel_token] 中发送令牌。但是在这种情况下你为什么要使用cookie呢?
    • Web 应用程序与应用程序源代码分开。 “api.example.com”是 api,“example.com”是 Web 应用程序
    • 并且您希望您的 api 使用 cookie 进行身份验证?
    猜你喜欢
    • 2017-12-14
    • 2019-01-25
    • 2020-11-20
    • 1970-01-01
    • 2023-03-15
    • 2017-05-31
    • 1970-01-01
    • 2023-03-14
    • 2021-12-21
    相关资源
    最近更新 更多