Monday, November 1, 2021

[SOLVED] Laravel rest api authentication

Issue

I am a beginner with building a rest api and authentication. I've just been reading the following and explains a very simple setup:

laravel 5 rest api basic authentication

At the bottom the article explains not to send usernames and password with headers or in the url.

My question is basicly: can anyone give me an example how to use a cUrl request with the example above?

For example:

$service_url = 'http://example.com/api/conversations';
$curl = curl_init($service_url);
$curl_post_data = array(
        'user' => '[email protected]',
        'passw' => '1234'
);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response = curl_exec($curl);

curl_close($curl);

Solution

Laravel is shipped with Guzzle – an advanced HTTP client library. It's probably more reasonable to use that than a low-level cURL.

To do basic auth with Guzzle:

$client = new GuzzleHttp\Client();
$response = $client->post('http://example.com/api/conversations', [
    'auth' => [
        '[email protected]', 
        '1234'
    ]
]);

The response will be in $response->getBody();

If your target endpoint uses SSL – it's not too bad sending the credentials in the headers, but the trendy way is to use temporary tokens (eg. API key or OAuth access token).



Answered By - Denis Mysenko