Consume an API that requires authentication with Laravel

Asked

Viewed 671 times

1

I’m creating an application with Laravel, which consists of consuming the Mcafee API.

The previous version was built in pure php, from which it consumed the data of a Mysql database powered by a Nodejs script that consumed the API.

The point is, the API requires authentication to consume the data, which was done with the Axios Auth method as below:

import axios from 'axios';
import https from 'https';
import sequelize from 'sequelize';

class requisitionController {
    async store(req, res) {
        try {
            const agent = new https.Agent({  
            rejectUnauthorized: false
            });
            const response = await axios.get('https://ePODirectory:port/remote/core.executeQuery?target=EPOLeafNode&select=(select%20EPOComputerProperties.ComputerName%20EPOComputerProperties.IPAddress%20EPOLeafNode.LastUpdate%20EPOComputerProperties.OSType%20EPOLeafNode.ManagedState%20EPOProdPropsView_EPOAGENT.productversion%20EPOProdPropsView_VIRUSCAN.datver)%22&:output=json', {
            httpsAgent: agent,
            auth: {
                username: '*********',
                password: '*********'
            }
            });

            const responseJSON  = JSON.parse(response.data.replace('OK:', ''));

            return res.json(responseJSON);
        } catch(err) {
            return res.json(err);
        }
    }
}

export default new requisitionController();

My question is, is it possible to consume this API with PHP/Laravel by performing this authentication?

Thank you in advance :-)

  • It is possible yes, you will use the guzzlehttp/guzzle to communicate with the destination API and on the route call you will pass the authentication parameters that the API needs.

3 answers

2


Yes it is possible, you should do something more or less like this:

Install the guzzle library to be able to consume the API.

composer require guzzlehttp/guzzle

Then you will consume the desired route.

$url = 'https://ePODirectory:port/remote/core.executeQuery?target=EPOLeafNode&select=(select%20EPOComputerProperties.ComputerName%20EPOComputerProperties.IPAddress%20EPOLeafNode.LastUpdate%20EPOComputerProperties.OSType%20EPOLeafNode.ManagedState%20EPOProdPropsView_EPOAGENT.productversion%20EPOProdPropsView_VIRUSCAN.datver)%22&:output=json';
$client = new GuzzleHttp\Client();
$client->request(
    'GET',
    $url,
    [
        'auth' = [
            'username',
            'password' 
        ]
    ]
);
  • I implemented the above code, but every time I run I have the following error: Undefined offset:0. To display the result I did the following: $Response -> receives the $client request, so I echo $Response->getBody(); I tested the request by Postman, and it went all right.

  • Try to get the result like this: $response->getBody()->getContents();

  • I read the documentation, Guzzle expects the username in index(0) and the password in index(1) of the Auth method. I just removed the fields "username" and 'password', leaving only the values of the same. It worked, but now I have a Certificate SSL error, but I believe it has to do with the internal network I use. Furthermore, it solved my problem :-)

0

Just complementing and bringing the syntax of version 8 of Laravel:

  1. Install the Guzzle:

    Composer require guzzlehttp/guzzle

  2. In the code you import and make a request (GET, POST...)

use Illuminate\Support\Facades\Http;

$response = Http::withToken('token')->post(http://example.com);
  1. Methods of a response instance:
$response->body() : string;
$response->json() : array|mixed;
$response->object() : object;
$response->collect() : Illuminate\Support\Collection;
$response->status() : int;
$response->ok() : bool;
$response->successful() : bool;
$response->failed() : bool;
$response->serverError() : bool;
$response->clientError() : bool;
$response->header($header) : string;
$response->headers() : array;

Source: https://laravel.com/docs/8.x/http-client

-2

Of course, since you pass the authentication keys during the request to the API, the advantage of using the Web Services API is that you can merge several different technologies.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.