I am learning Laravel but I'm encountering a real-world situation that I'm a bit stumped by.
I have my own REST API that performs a lot of critical functions. Although I execute the majority of my REST calls through a front-end that works together with the backend, there are times when I wish to make calls to my REST API via terminal curls or scripting (ex. curl -X POST -d "message[_token]=123" -d "message[body]=hello world" 'http://my_rest_api.com') on my local machine.
As I currently understand it, if I want to make a call to my Laravel REST API, I must pass a token (which I've done successfully by pulling the session token). My question is, is there a practical way to retrieve a token from my backend and then try to POST from a script on my local machine? Or is there some sort of, global token (like my app key) that I can encrypt and pass and laravel will recognize me as authorized to POST?
I understand I can disable the token on the specific route, but I don't want to do this, because I would like to keep my REST calls locked down.
You may do by using HTTP HEADER. All you have to is to create a middleware that authenticate HTTP Header your route before response.
#Your Middleware AuthAPI
public function handle($request, Closure $next)
{
//every request you send it checks your request header X-API-KEY match with your application secret key
if($request->header("X-API-KEY") == env("APP_KEY")){
return $next($request);
}else{
return response()->json(['error_code' => 403, 'message' => 'API Key is required']);
}
}
After creating this middleware class all you need to do is to add this in your routers.
Example:
Route::put('/login', ['middleware' => ['AuthAPI'], function () {
//do something here
}]);
I hope you understand it and this may work well as per your need.
So using the middleware above, I can verify the token passed in the headers as authorized -- awesome!
My question then is, could I work this middleware response to then bypass Laravels token auth? Or would I have to disable token auth on all my routes and use the API key middleware above as a workaround?
EDIT: I messed around and realized I could verify the API key, if it matches I could add the current session token value to the incoming request header, thus ensuring that anytime anyone makes a call with the api key (but not the token key), the key will be appended regardless.
You can work with your middleware you can by pass laravel token because your API KEY is unique and without this no one can make request to your API server until you provide them you API Key and you can use database api key for specific users.
And to match current session is great idea to make more secure request. And sorry for the late reply because weekends was going on :)