[Vuejs]-Token-based Authentication Laravel 5.5

0👍

As Maraboc already said, you should start by creating a column api_token: $table->string('api_token', 60)->unique(); in your users table.

Make sure each newly created user gets a token assigned, and encrypt it: $user->api_token = encrypt(str_random(60));

Next, you could define a Javascript variable in the footer of your app:

window.Laravel = <?php echo json_encode([
    'apiToken' => !empty(Auth::user()) ? decrypt(Auth::user()->api_token) : ''
]); ?>;

Later, when you want to make a request to an endpoint, you should add a header, authorizing the user:

let url = '/path/to/your-endpoint.json';
let data = {
    headers: {
        'Authorization': 'Bearer ' + Laravel.apiToken
    }
};

axios.get(url, data)
    .then(response => console.dir(response));

Finally, in your controller, you can get your User instance by using Laravel’s guard:

$user = !empty(Auth::guard('api')->user()) ? Auth::guard('api')->user() : null;

Hope this helps! BTW: these articles helped me on my way:

0👍

The solution I took was to not put ajax endpoints in the api namespace. By putting them as web routes instead of api it’ll use CSRF (cross-site request forgery) protection to validate the route. So only if it comes from my domain will it be authenticated. This is ONLY useful when the site is served in https.

👤Ben

Leave a comment