Laravel - Send api_token within the header - api

I'm building an API for Laravel and I want to send the api_token within the header instead of the form post. Is this something that is already built in or would I have to go the route of figuring out how to create my own auth driver?

After struggling a little with this myself I got it working.
You need to first follow this little tutorial on how to use the api_token for your laravel API:
https://gistlog.co/JacobBennett/090369fbab0b31130b51
Then once you have the api_token in the users table etc you can now pass this in the header of each request.
My laravel is using the Vueify templates, ie I have under /components/Comment.vue etc files.
First step is to pass the users api_token to the Vue Template by passing a property through the component definition in your blade template:
<comments id_token="{{ access()->user()->api_token }}"></comments>
Then ensure in your .vue file that you accept the property by adding it to the "props":
export default {
data: function() {
return {
edit: false,
list: [],
comment: {
id: '',
name: '',
body: ''
}
};
},
props: ['id_token'],
created: function() {
Vue.http.headers.common['Authorization'] = 'Bearer ' + this.id_token;
this.fetchCommentList();
},
Notice above that I also added the token to the common headers in order to have it go through each request used in all the methods further down.
Vue.http.headers.common['Authorization'] = 'Bearer ' + this.id_token;

If you are consuming your API, you don't need to create an auth driver, you need to make requests to your API endpoints. Choose the method you prefer, and make requests, don't think as the same way when you use the auth driver at a webpage.
This is an example how send the $token through the headers. With cURL and Guzzle
$data = [
'value1' => 'value1',
'value2' => 'value2'
];
With CURL
$headers = [
'Authorization: Bearer '.$token
];
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, 'http://api.domain.com/endpoint');
curl_setopt($ch2, CURLOPT_POST, 1);
curl_setopt($ch2, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch2, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec ($ch2);
curl_close ($ch2);
With Guzzle
$headers = [
'Authorization' => 'Bearer '.$token
];
$client = new GuzzleHttp\Client();
$res = $client->request('POST', 'http://api.domain.com/endpoint',[
'form_params' => $data,
'headers' => $headers,
]);
I hope this helps!

Related

How save token in request for não get everytime request?

this my method
public function postOrUpdateProductRd($payload)
{
$payload = json_encode($payload);
$access_token = $this->authenticate->result->access_token;
$this->header = [
'content-type' => 'application/json',
'Authorization' => ' Bearer ' . $access_token,
];
$response = Http::withHeaders($this->header)->post($this->urlBase . $this->endPoint, $payload);
}
How could I save the token I get there to use it until it expires. And how to check if it is expired?
it comes like this when I run the request:
^ {#46
+"token_type": "bearer"
+"access_token": "zurUe8QF386NSyljiTbkXCdcUAZ8rIal"
+"expires_in": 7200
}
I need to store the token somehow to use until it requests a new one as it has expired.
I'm a beginner at this sorry if I was reductive.

Baselinker Api Call from Google App Script

I struggle to connect to third party api (Baselinker Api) from my App Script.
function makeHttpPostRequestWithAppsScript() {
const url = "https://api.baselinker.com/connector.php?method=getOrders";
const response = UrlFetchApp.fetch(url, {
"method": "POST",
"headers": {
"X-BLToken": "xxxx",
"Content-Type": "application/json"
},
"muteHttpExceptions": true,
"followRedirects": true,
"validateHttpsCertificates": true,
"contentType": "application/json",
"payload": JSON.stringify({"order_id":"5131"})
});
Logger.log("Response code is %s", response.getResponseCode());
Logger.log(response.getContentText());
}
Any idea where am I going wrong? Of Course token is ok.
I am getting error like that :
Informacje {"status":"ERROR","error_code":"ERROR_UNKNOWN_METHOD","error_message":"An empty or unknown method has been used"}
That is what it should look like in PHP
<?php
$methodParams = '{
"date_confirmed_from": 1407341754,
"get_unconfirmed_orders": false
}';
$apiParams = [
"method" => "getOrders",
"parameters" => $methodParams
];
$curl = curl_init("https://api.baselinker.com/connector.php");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, ["X-BLToken: xxx"]);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($apiParams));
$response = curl_exec($curl);
Thanks
I believe your goal is as follows.
You want to convert the following PHP script to Google Apps Script.
<?php
$methodParams = '{
"date_confirmed_from": 1407341754,
"get_unconfirmed_orders": false
}';
$apiParams = [
"method" => "getOrders",
"parameters" => $methodParams
];
$curl = curl_init("https://api.baselinker.com/connector.php");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, ["X-BLToken: xxx"]);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($apiParams));
$response = curl_exec($curl);
When I saw your PHP script, it seems that the data of $methodParams is sent as the form data. So, in this case, how about the following modification?
Modified script:
function makeHttpPostRequestWithAppsScript() {
const url = "https://api.baselinker.com/connector.php";
const response = UrlFetchApp.fetch(url, {
"method": "POST",
"headers": { "X-BLToken": "xxxx" },
"muteHttpExceptions": true,
"payload": {
"method": "getOrders",
"parameters": JSON.stringify({ "order_id": "5131" }),
}
});
Logger.log("Response code is %s", response.getResponseCode());
Logger.log(response.getContentText());
}
Note:
When I saw your sample PHP script and your Google Apps Script, in your PHP script, {"date_confirmed_from": 1407341754,"get_unconfirmed_orders": false} is used as the value of parameters. But, in your Google Apps Script, {"order_id":"5131"} is used. If your sample PHP script works fine and when the above modified Google Apps Script didn't work, please test for replacing {"order_id":"5131"} with {"date_confirmed_from": 1407341754,"get_unconfirmed_orders": false} and test it again.
I thought that if {"date_confirmed_from": 1407341754,"get_unconfirmed_orders": false} is used to the above Google Apps Script, it seems that the request is the same with your PHP script. So, if an error occurs, please check each value and your token, again.
This modified script supposes that your sample PHP script works. Please be careful about this.
Reference:
fetch(url, params)

Send Body React Native - PHP

I am sending the clientid variable in my React-native project. I am sending the body using the post method when posting.But now the clientid variable is not going to php, it sends a null value.
React-Native Code
let rspNew = await get3dNumber({
clientid: "500300000",
...
})
export function get3dNumber(CART){
return fetch(`http://...php`,{
method:'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect:'follow',
body:JSON.stringify(CART)
})
}
PHP CODE
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With");
$json = json_decode(file_get_contents('php://input'), true);
$myArray = array();
$myArray['clientid'] = $json['clientid'];
?>

How to send POST requests to the VK API

I have a VK bot that needs to send long messages. They do not fit in URI, if I try to send a GET request, API returns URI too long error. Sending requests with Content-Type: application/json and passing json as body doesn't work, neither is it possible to send a Content-Type: multipart/form-data request. Is it possible to send a POST request to VK API?
It is possible to send a POST request using Content-Type: application/x-www-form-urlencoded;charset=UTF-8. Also it's recommended to send access_token and v parameters in url and the rest in the body.
Example in JavaScript:
const TOKEN = '...'
const VERSION = '5.126'
fetch(`https://api.vk.com/method/messages.send?access_token=${TOKEN}&v=${VERSION}`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
random_id: Math.round(Math.random()*100000),
peer_id: 185014513,
message: 'Hello world'
}).toString()
})
.then((res) => res.json())
.then(console.log)
In PHP:
const TOKEN = '...';
const VERSION = '5.126';
$query = http_build_query([
'access_token' => TOKEN,
'v' => VERSION,
]);
$body = http_build_query([
'random_id' => mt_rand(0, 100000),
'message' => 'Hello world',
'peer_id' => 185014513,
]);
$url = "https://api.vk.com/method/messages.send?$query";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_HTTPHEADER , [
'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8',
]);
$response = curl_exec($curl);
curl_close($curl);
$json = json_decode($response, true);
Note that you cannot send messages over 4096 characters long

Laravel 5 API not allowing access to new Angular2 app

I have a Laravel API which is now allowing a new Angular2 application I am building to have access to itself. I get the following error:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3073' is therefore not allowed access. The response had HTTP status code 404.
This is confusing me quite a bit as I already have two applications (one also an Angular2) application that is communicating with the API fine with no issues whatsoever. I have also created CORS middleware in the API which provides the appropriate headers to allows these applications through.
CORS Middleware
<?php
namespace App\Http\Middleware;
use Closure;
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
class CORS {
public function handle($request, Closure $next) {
header("Access-Control-Allow-Origin: *");
$headers = [
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
];
if($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value) {
$response->header($key, $value);
}
return $response;
}
}
My Angular2 application is attempting to call my API using this code:
import { Injectable } from "#angular/core";
import { Http, Headers, RequestOptions } from "#angular/http";
import { Observable } from "rxjs";
#Injectable()
export class AuthService {
constructor(private _http: Http) {
}
login(loginDetails):Observable {
let body = JSON.stringify(loginDetails);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.post('http://#####-brain.dev/api/v1', body, options)
.map(res => res.json());
}
}
Does anyone have any advice as to why this particular application is not receiving the Access-Control-Allow-Origin header header? I have put a breakpoint within my CORS middleware and it doesn't hit it at all which is bizarre as it is calling exactly the same endpoint that my other application is and that is working fine.
I have also noticed that it is only POST requests that it doesn't allow through.
Edit: Here is my app/Http/Kernel.php file in the Laravel API:
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'cors' => 'App\Http\Middleware\CORS',
'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class
];
Thanks!