Now that we have created an authentication page and can log in the user, we need to protect the routes, both on the front-end and back-end. So let's implement auth:sanctum Middleware.
Protect Back-end API Calls
We have installed Sanctum earlier with the install:api Artisan command. Now, we can update the API routes to use the auth:sanctum Middleware.
routes/api.php:
Route::get('/user', function (Request $request) { return $request->user();})->middleware('auth:sanctum'); Route::group(['middleware' => 'auth:sanctum'], function() { Route::apiResource('posts', PostController::class); Route::get('categories', [CategoryController::class, 'index']); Route::get('/user', function (Request $request) { return $request->user(); });});
Next, we need to redirect the user to the login page, on the front-end. We need to...
Hi Povilas, Thank you for your great lessons. According to the vue-router doc, the
nextfunction should be called exactly once otherwise the hook will never be resolved or produce errors.function auth(to, from, next) { if (JSON.parse(localStorage.getItem('loggedIn'))) { next() } else { next('/login') } }
[Navigation Guards | Vue Router]https://v3.router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards)