登录操作后在 Guzzle HTTP 客户端中设置授权承载 header - Laravel

Set the Authorization Bearer header in Guzzle HTTP client After Login Action - Laravel

我目前正在做一个 laravel 项目,向 API 提出请求。 每个对端点的请求都需要 header.

中的令牌

我创建了一个登录函数,当登录成功时,我想在 header 中为每个对端点的请求放置一个令牌。

我可以使用 Guzzle 做到这一点吗?

这是我的登录功能

public function login(Request $request)
{
    $client = new Client();
    $url = "http://localhost:8002/login";

    $request = $client->post($url, [
        'headers'=> ['Content-Type' => 'application/json'],
        'body' => json_encode([
            'email' => $request->email,
            'password' => $request->password,
        ])
    
    ]);

    $response = json_decode($request->getBody());
    $token = $response->result->token; //I have got the token
    

}

根据您的情况,您应该使用任何数据存储在成功登录后保留您的授权令牌。 Session 商店将是一个好的开始。

另外,根据您的 API 使用的授权类型(Bearer token、Basic auth...),将 header 添加到 Guzzle 请求将如下所示:

$request = $client->post($url, [
    'headers'=> ['Authorization' => 'your auth header with auth token'],
    'body' => json_encode([
        'foo' => 'bar',
    ])

]);