2
votes

I have Laravel application with VUEJS as front-end, I am getting data by creating API Routes. So for example the route for getting posts data will be http://localhost/api/posts

What is the best way to protect my routes?

I saw on laravel documentation that there is: API athentication https://laravel.com/docs/5.8/api-authentication also Passport https://laravel.com/docs/5.8/passport

For example now any user can reach to the route http://localhost/api/posts and he will get json with all posts data.

I want protect that and allow only inner api request from my VUEJS commponent to get the data

2

2 Answers

6
votes

I’m assuming you’re going to use the Laravel auth routes to do the authentication, and after the authentication, the next view you’re reaching is the one with all the Vue components.

The solution is simple, even that is on the documentation, the necessary steps should be clarified.

We need to:

  1. Add passport composer require laravel/passport
  2. Make the migrations php artisan migrate
  3. Install passport php artisan passport:install

The fourth step is more complex. We need to open our User.php model file. And first we need to import the HasApiTokens and tell the model to use it.

use Laravel\Passport\HasApiTokens;

class User extends Authenticatable

{

    use HasApiTokens, Notifiable;

    .......

}

Then on our config/auth.php we need to modify the api array and change the driver to passport

'api' => [

    //for API authentication with Passport

    'driver' => 'passport',

    'provider' => 'users',

],

Then on our app/Http/Kernel.php we need to add a middleware to the $middlewareGroups array in the key web.

protected $middlewareGroups = [

    'web' => [

        ................

        //for API authentication with Passport

        \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,

    ],

Now we can use the auth:api middleware on our api routes.

Route::middleware('auth:api')->group( function(){
    ...your routes here
});
2
votes

This is what the CSRF TOKEN doing, it's not quite the same with the API Authorization doing

CSRF Token:

To protect (inner) API or access points from cross-site accessing, See Cross-site_request_forgery

CSRF Token is expired and generated within a randomly time, which will make the program access difficulty

API Authorization:

The API is design to be used from other programs, and you'd like to protect them from non-authorized access

Since API tokens expiration and generation is handle by admin manually, since you'll need to place this API token in your HTML to get your function working, it's not what you searching for here


More details of CSRF protection in Laravel see: Laravel CSRF production document

Generally, we'll protect all the routes POST and PUT routes by default