Sometimes, when you are creating a web app, you might want to create some routes for your API.
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Or
Route::middleware('auth:api')->group(function(){
Route::get('users', "UserController@index");
Route::post('users', "UserContoller@save");
Route::get('home', function(){
return 'something';
});
});
Laravel fortunately, laravel makes this easy by shipping with a
routes/web.php
and routes.api.php
file. TheTheroutes/web.php
file defines routes that are for your web interface. These routes are assigned theweb
middleware group, which provides features like session state and CSRF protection. The routes inroutes/api.php
are stateless and are assigned theapi
middleware group.
api
middleware helps you to guard your api
routes and you can easily guard multiple routes by defining as follows:Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Or
Route::middleware('auth:api')->group(function(){
Route::get('users', "UserController@index");
Route::post('users', "UserContoller@save");
Route::get('home', function(){
return 'something';
});
});
After creating and setting up your routes and it's guard, now you'll need to authenticate users making calls to your API. You might possibly want to use Laravel Passport or other sophisticated means of authentication, but the purpose of this tutorial is to show you a simple method and still relatively secure.
Step 1:
Add an api_token column to your users table
$table->string('api_token')
You can fill this column manually or create a random string for every new user signing up
Tip:
str_random(60)
Step 2:
On every call to your api routes, add the query parameter
?api_token=[your_api_token]
and laravel will automatically compare the token to the one in the database
It's that simple.
0 comments:
Post a Comment
Say something...