samedi 10 août 2019

How to combine Session and API authentication in Laravel?

I have a simple project that has only 3 tables. The users, table2, and table3.

The User schema

Schema::create('users', function (Blueprint $table) {
  $table->bigIncrements('id');
  $table->string('username')->unique();
  $table->string('password');
  $table->string('api_token')->unique();
  $table->rememberToken();
  $table->timestamps();
});

The other 2 tables are accessible via API resource.

Here are my routes:

routes/web.php

Route::get('/', 'Auth\LoginController@showLogin')->name('login');
Route::post('/login', 'Auth\LoginController@login');
Route::get('/logout', 'Auth\LoginController@logout')->name('logout');
//Authenticated users will be redirected here
Route::get('/home', 'HomeController@index')->name('home');

routes/api.php

Route::resource('/table1', 'Table1Controller');
Route::resource('/table2', 'Table2Controller');

I've added the auth:api middleware in the Table1Controller and Table2Controller.

public function __construct()
{
    $this->middleware('auth:api');
}

So I only have 2 pages to be exact. The main page where the authenticated user goes to and the login page.

When a user is added, it also saves a random string api_token to it's row.

I am using VueJS and I don't want to make a mess and use Node with this one. So I've downloaded the vue.min.js and just include it in my blade files.

So when you login, you will be redirected to /home page. The layout page of my pages has this one:

<script src=""></script>
<script src=""></script>
<script>
const user = @json(Auth::user());

const http = axios.create({
  baseURL: '/api',
  headers: {
    'Authorization': user ? 'Bearer ' + user.api_token : ''
  }
});
</script>

With the code above, you should be able to access the table1 and table2 apis when you send a request.

Now I know I could've just used webpack and make my app a SPA and just use passport or maybe just jwt. But I don't want since it's a very simple app and I want to do actions without refreshing my pages like adding data in table, editing data and show it in a model, etc.

Is there a better way of doing this that I am missing? Any help or suggestions would be highly appreciated. Thank you.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire