Laravel rest api authentication - rest

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' => 'user#user.com',
'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);

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' => [
'user#user.com',
'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).

In addition to the accepted answer, you can also create a generic function to handle all your curl requests.
You can use the following function to call external webservices and return the data/authentication information.
/*=============================================
* Call External Webservices using CURL
*
* #param $requestURL, $header -> (OPTIONAL)
* #return json
#=============================================*/
public function curlRequest($requestURL, $headers = array())
{
$getData = curl_init($requestURL);
curl_setopt($getData, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($getData, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($getData, CURLOPT_SSL_VERIFYHOST, false);
if (count($headers) != 0) {
curl_setopt($getData, CURLOPT_HTTPHEADER, $headers);
}
$response = curl_exec($getData);
return json_decode($response);
}
Use case specific example to use the above function for authentication:
$requestURL = 'http://www.example.com/api/userLogin';
$userAuthInfo = [
'email'=> 'example#example.com',
'password'=>'123456'
];
$result = $this->curlRequest($requestURL, $userAuthInfo);
dd($result); //Print the Result of the Authentication request

Related

x-api-key in header still gives Forbidden response (AWS lambda function)

I have a Lambda function on AWS for which I have created a trigger with Security. I set the url ($url) to be the API endpoint listed in the "triggers" section of the lambda function, and the x-api-key (instead of my_api_key below) to be the one listed in the trigger "API key".
However, if I try to make a simple call to the lambda function like so:
$url = "https://abcd1234.execute-api.us-east-2.amazonaws.com/default/lambda_function_name";
$header = array(
"Content-Type" => "application/json",
"Accept" => "application/json",
"x-api-key" => "my_api_key",
);
$data = array(
"email_address" => $_POST['email'],
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, json_encode($header));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($curl);
curl_close($curl);
I obtain the response "Forbidden".
What is the issue here?
Is there some AWS configuration I need to change?
Or is the syntax or place to add the x-api-key wrong?
Thanks in advance!
Maithreya
I am assuming you are connecting to AWS API Gateway. Your endpoint URL must include the stage and resource, i.e.:
https://abcd1234.execute-api.us-west-2.amazonaws.com/prod/send_email_alert
Calling the API gateway base endpoint URL will result in this error.

Sendgrid Unsub For Only Specified Group

I am using sendgrid unsub api's for who does not want the campaign e-mails.
But when I send request for unsub the email, the adress goes to global unsub list.
Here is my php code
$parameters = array(
"api_user" => self::EMAIL_USER_NAME,
"api_key" => self::EMAIL_PASSWORD,
"email" => $email,
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $parameters);
$json_response = curl_exec($curl);
How to specify an unsub group id for api call?
It looks like you're using the V2 API right now. Unsub groups are only available via the V3 API, using the suppressions endpoint.
In V3, you POST addresses to the resource URL of the unsub group, for example, https://api.sendgrid.com/v3/asm/groups/:group_id/suppressions
Keep in mind that to use V3 you'll need to use the updated authentication schema that uses an Authorization header and a real API key.

Connect Yii2 to another RESTful application

I have a Yii2 application. I would like to connect it to another restful webpage. So user will send data to my application, I will send them via POST request and do something according to a JSON response. How can I do the send a request / fetch response part in a yii2?
The best method would be to use curl to make end to end calls to your RESTful API, in which case you may be interested in checking out a yii2 extension for curl.
Without a Yii2 extension, we can accomplish this by creating a more general function in a controller or more preferably a model (for shared access) as exampled below:
/**
* $method e.g POST, GET, PUT
* $data = [
'param' => 'value',
]
*/
public function curlToRestApi($method, $url, $data = null)
{
$curl = curl_init();
// switch $method
switch ($method) {
case 'POST':
curl_setopt($curl, CURLOPT_POST, 1);
if($data !== null) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
break;
// logic for other methods of interest
// .
// .
// .
default:
if ($data !== null){
$url = sprintf("%s?%s", $url, http_build_query($data));
}
}
// Authentication [Optional]
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
We then call this function on a need basis i.e. depending on the method and url and/or data.
It is also conveniently easy to use file_get_contents if fopen wrapper is enabled in order to access Web Service URLs.
$response = file_get_contents('http://example.com/path/to/api?param1=stack&param2=overflow');
If a JSON response is served, you can recover the php array as follows:
$response = json_decode($response, TRUE);
If an XML response is returned, then
$response = new \SimpleXMLElement($response);
However, if the API endpoint returns an HTTP error status, the file_get_contents function fails with a warning and returns null.

Translate cURL request to Guzzle

I am trying to use Guzzle instead of directly using cURL to achieve and HTTP request. How do I make this same type of request but with Guzzle? Or should I just stick to cURL?
$ch = curl_init();
// Set the URL
curl_setopt($ch, CURLOPT_URL, $url);
// don't verify SSL certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// Return the contents of the response as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Follow redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
// Set up authentication
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$token:X");
I keep running into 401 Unauthorized error. I know I have correct credentials. What makes me think I am not on the right track is the Guzzle docs stating: auth is currently only supported when using the cURL handler, but creating a replacement that can be used with any HTTP handler is planned. But from my understanding Guzzle defaults with cURL.
$guzzleData = [
'auth' => [$token, 'X'],
'allow_redirects' => true,
'verify' => false,
];
$client = new \Guzzle\Http\Client();
$request = $client->get($url, $guzzleData);
$response = $request->send();
Here is the solution:
$client = new \Guzzle\Http\Client();
$request = $client->get($url);
$request->getCurlOptions()->set(CURLOPT_SSL_VERIFYHOST, false);
$request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false);
$request->getCurlOptions()->set(CURLOPT_RETURNTRANSFER, true);
$request->getCurlOptions()->set(CURLOPT_FOLLOWLOCATION, true);
$request->getCurlOptions()->set(CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$request->getCurlOptions()->set(CURLOPT_USERPWD, "$token:X");
$response = $request->send();
The solution I was able to get working for Guzzle6 is:
$headers = array();
$headers['grant_type'] = 'client_credentials';
$headers['client_id'] = $clientid;
$headers['client_secret'] = $clientSecret;
$response = $this->client->post($urlAuth, ['form_params' => $headers]);
$output = $response->getBody()->getContents();
ie the header array has to be wrapped in 'form_params'

SugarCRM REST api error

I am trying to retrieve custom module data through the Sugarcrm REST api but I am not able to do so as I am not even able to login with the documentation code, I tried same thing as given in documentation
<?php
// specify the REST web service to interact with
$url = 'localhost/~jmertic/sugarcrm/service/v4_1/rest.php';
// Open a curl session for making the call
$curl = curl_init($url);
// Tell curl to use HTTP POST
curl_setopt($curl, CURLOPT_POST, true);
// Tell curl not to return headers, but do return the response
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the POST arguments to pass to the Sugar server
$parameters = array(
'user_auth' => array(
'user_name' => 'username',
'password' => md5('password'),
),
);
$json = json_encode($parameters);
$postArgs = array(
'method' => 'login',
'input_type' => 'JSON',
'response_type' => 'JSON',
'rest_data' => $json,
);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($curl);
// Convert the result from JSON format to a PHP array
$result = json_decode($response);
if ( !is_object($result) ) {
die("Error handling result.\n");
}
if ( !isset($result->id) ) {
die("Error: {$result->name} - {$result->description}\n.");
}
// Get the session id
$sessionId = $result->id;
changed the username,password and url to match my setup but i get an error stating
No direct script access allowed
I tried to search this on web but couldnt find any relevant solution.
I am using sugarCRM 6.5.0RC2 version
Regards,
Anand Joshi
You probably has some defense configured on your WEB server which allows you to access only to index.php.
To verify it, try to go from the browser to your API URL: http://YOUR_DOMAIN_NAME/service/v4_1/rest.php
Or/and run from terminal: wget http://YOUR_DOMAIN_NAME/service/v4_1/rest.php
If it shows the same message, check your .httaccess on this folder or/and your web server config file.
If no, how do you run the API test script? through CLI or from browser?
Also I suggest you to use some Open Source SugarCRM REST API Wrapper. I use this one: https://github.com/asakusuma/SugarCRM-REST-API-Wrapper-Class
Shouldn't the line be this...
$url = 'http://yoursugarinstance/service/v4_1/rest.php';