Simple API_Token Auth for VueJS Components and Laravel

Posted: 2018-06-27 16:18:13

For those non Passport moments just a simple site that has VueJS Components that need to access routes with authentication in place.

Thanks to

Route File

routes/api.php

Route::get('/trigger_contacts', function (Request $request) {
    \Log::info("Triggering Contacts");
    return response()->json(null, 200);
})->middleware('auth:api');

This will not work out of the box, you will get a 401. Let's plug some things in.

Blade

My main resources/views/layouts/app.blade.php

    <script>
        window.Laravel = {!! json_encode([
                "apiToken" => auth()->user()->api_token ?? null
        ]) !!};
    </script>
</head>

Okay now for VueJS

resources/assets/js/bootstrap.js

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.headers.common['Authorization'] = 'Bearer ' + Laravel.apiToken;

Now the migration and model

php artisan make:migration alter_users_add_api_token --table=users

Then the migration file:

        Schema::table('users', function (Blueprint $table) {
            $table->char('api_token', 60)->nullable()->after('remember_token');
        });

And the User.php model (which is not in the App\Model folder :) ):

    protected $hidden = [
        'password', 'remember_token', "api_token"
    ];

    public function getApiTokenAttribute($value)
    {
        if (!$value) {
            $value = str_random(60);
            $this->api_token = $value;
            $this->save();
        }

        return $value;
    }

Component

This is nothing out of the ordinary:

    triggerContacts() {
      this.loading = true;
      axios
        .get('/api/trigger_contacts')
        .then(results => {
          console.log(results);
          this.status_message = 'Triggered Contacts';
          setTimeout(() => {
            this.loading = false;
            this.status_message = null;
          }, 3000);
        })
        .catch(err => {
          console.log('issue with trigger');
        });
    }

That is it now your component will work with the route.


Tags:

vuejs laravel