[Vuejs]-Any Idea how to do Session based authentication in laravel 5.3 using vue js and vue router

2👍

If you’re using Laravel as an API, you’ll likely want to do token-based authentication. The main idea is to use the ‘api’ guard (which uses the TokenGuard class), instead of the default ‘web’ guard (you can change this in congif/auth.php). This way Laravel will look for a Bearer token in the Authorization header in each request.

This is a decent walk through to get started, though I’m sure there are many other good blog posts and tutorials out there.

EDIT:

Not sure if this is helpful, but here’s an example using an automated test. In my ModelFactory, I have a user model with an api_token attribute which is set to a random (and unique) string of 60 characters. This is a simple test to make sure I can retrieve a list of users:

/** @test */
public function user_index_endpoint_returns_list_of_users()
{
    $user = factory(User::class)->create();

    $this->get('/users', array(
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $user->api_token
            ))
         ->assertResponseStatus(200)
         ->seeJsonStructure([
            'users'
         ]);
}

At the top of my config/auth.php file, I’ve set my default guard to ‘api’:

'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],

Finally, in my routes file I’ve set up my users route to use the ‘auth’ middleware.

Route::group(['middleware' => 'auth'], function() {
    Route::get('/users', 'UsersController@index');
});

Because I’ve defined the ‘api’ middleware as my default, behind the scenes Laravel will use the TokenGuard class to try to authenticate my request. To do so, it will look for a bearer token in my request and compare that against the users table.

Leave a comment