📜  auth laravel 7 - Javascript (1)

📅  最后修改于: 2023-12-03 15:29:32.101000             🧑  作者: Mango

Auth Laravel 7 - Javascript

In Laravel 7, the authentication scaffoldings have been separated from the core framework. This means you need to install the authentication scaffolding using the following command:

composer require laravel/ui
php artisan ui vue --auth
npm install && npm run dev

This command installs the Laravel UI package, and generates the authentication scaffolding using Vue.js.

Configuring the Authentication routes

After generating the scaffolding, Laravel will create various authentication routes. These routes are defined in the routes/web.php file. You can see the authentication routes by running the following command:

php artisan route:list

Notice that the authentication routes are defined under the auth middleware.

Route::middleware('auth')->group(function () {
    Route::get('/home', 'HomeController@index')->name('home');
});
Customizing the Authentication views

Laravel 7 generates all the authentication views for you, but sometimes you may need to customize them. The generated views are located at the resources/views/auth directory. You can copy these views to your resources/views directory, and then modify them as needed.

Handling Authentication with Javascript

When it comes to authentication in Javascript, there are a few things you need to be aware of.

Firstly, after the user logs in, you will need to store the authentication token somewhere. You can use localStorage or sessionStorage to store the token in the browser.

// After successful login
localStorage.setItem('token', response.data.token);

Secondly, you will need to send the authentication token with every request to your API. You can do this using the Authorization header.

// Add authorization header
axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('token');

Finally, you may need to redirect the user to the appropriate page based on their authentication status. In Vue.js, you can use the beforeEach method to check the user's authentication status before routing them to a page.

// Route guard
router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.requiresAuth)) {
        if (!localStorage.getItem('token')) {
            next('/login');
        } else {
            next();
        }
    } else {
        next();
    }
});

With these tips, you can handle authentication in Laravel 7 and Javascript effectively.