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

Viewed 5776

I'm currently working on a laravel project to make a request to the API. Every request to an endpoint requires a token in the header.

I created a function for login, when login is successful I want to put a token in the header for each request to the endpoint.

Can I do that using Guzzle?

This is my function for login

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
    

}
1 Answers

Depending on your case you should use any data store to keep your authorization token after successful login. Session store would be a good start for that.

Also depending on the type of authorization your API is using(Bearer token, Basic auth...) adding header to the Guzzle request will look like:

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

]);
Related