You are currently viewing Laravel  Authentication using Laravel Jetstream
Laravel 10 Authentication using Laravel Jetstream

Laravel Authentication using Laravel Jetstream

Laravel Jetstream is a beautifully designed application starter kit for Laravel and provides the perfect starting point for your next Laravel application. Jetstream provides the implementation for your application’s login, registration, email verification, two-factor authentication, session management, API via Laravel Sanctum, and optional team management features.

Jetstream is designed using Tailwind CSS and offers your choice of Livewire or Inertia scaffolding.

In this tutorial I will show you, How to create a Powerful authentication system using Laravel Jetstream & Livewire 3.

Installing Laravel

First we need to install Laravel. Open your terminal and enter one of the below command to install Laravel.

composer create-project laravel/laravel example-app

Or enter the below command to install Laravel using Laravel Global Installer

laravel new example-app

Here I will name the app jetsream_auth, so I will install Laravel using following command :

laravel new jetstream_auth

The installation will take some time depending on your internet connection.

Creating a Database

Now open PhpMyAdmin & create a Database called “jetstream_auth”. Open .env file and add the database name inside it.

Installing Laravel Jetstream

After Laravel installation completes, we will install Jetstream package.

Go to your project directory by typing cd your_project and enter the below command to install Laravel Jetstream:

composer require laravel/jetstream

Installing Front End stack

After installing Jetstream package we need to install Front end stack for our app. You can install either Livewire or Inertia for your front end stack. We will install Livewire in this tutorial, so open your terminal & enter below command to install Livewire

php artisan jetstream:install livewire --dark --teams --pest

In the above command we have used teams , dark & pest flags.

The –teams flag will be used to enable team support.

The –dark flag will be used to include dark mode in our App.

The –pest flag will be used to install a Pest test suite instead of the default PHPUnit test suite.

Installing Dependencies

After installing Front End stack for Jetstream, we need to install and build NPM dependencies .

Enter below command in your terminal to install the dependencies :

npm install

Now enter below command to compile your application’s frontend assets:

npm run dev

We need to keep this tab running , do not close it.

Migrating Database

Now we need to migrate the database. Open a new terminal and enter the below command to migrate the database :

php artisan migrate

Running the App

Now open a new terminal & enter below code to run the app :

php artisan serve

Now go to your browser & type the url localhost:8000

It will open welcome page with Register & Login link.

Registering the User

Click on the Register link, enter your details & click on Register.

After you register, you will be redirected to the Dashboard page.

In the right side you can sea Dropdown with your name, click on it to expand.

You can see there are three links in this dropdown :

Profile, API Token & Log out.

If you click on profile link, Profile Page will be opened. Here you will see Profile Information,  Update Password, Two Factor Authentication, Browser Sessions & Delete Account Sections.

Profile Information

In this section you can update your name and email

Update Password

In this section you can update your password.

Two Factor Authentication

Laravel Jetstream automatically scaffolds two-factor authentication support for all Jetstream applications.

When a user enables two-factor authentication for their account, they should scan the given QR code using a free TOTP authenticator application such as Google Authenticator. In addition, they should store the listed recovery codes in a secure password manager such as 1Password.

If the user loses access to their mobile device, the Jetstream login page will allow them to authenticate using one of their recovery codes instead of the temporary token provided by their mobile device’s authenticator application.

Browser Sessions

This feature utilizes Laravel’s built-in Illuminate\Session\Middleware\AuthenticateSession middleware to safely log out other browser sessions that are authenticated as the current user.

Session Driver

To utilize browser session management within Jetstream, ensure that your session configuration’s driver (or SESSION_DRIVER environment variable) is set to ‘database’.

Delete Account

In this section the user can delete. When the user clicks on the Delete button, a modal will be open for confirmation. The user needs to enter his password to delete his account.

Enable Terms & Privacy Policy

Many applications require users to accept their terms of service / privacy policy during registration. Jetstream allows you to easily enable this requirement for your own application, as well as provides a convenient way of writing these documents using Markdown.

To get started, enable this feature in your application’s config/jetstream.php configuration file:

To do so uncomment Features::termsAndPrivacyPolicy(), in Jetstream.php file.

Now When a user tries to Register, a check box will be displyed for Terms & Privacy policy before the Register button. The user must accept the terms & privacy policy to get registered.

Laravel 10 Authentication using Laravel Breeze

Enabling Profile Photos ​

If you want to allow users to upload custom profile photos, you must enable the feature in your application’s config/jetstream.php configuration file. To enable the feature, simply uncomment the corresponding feature entry from the features configuration item within this file:

Features::profilePhotos(),

After enabling the profile photo feature, you should execute the storage:link Artisan command. This command will create a symbolic link in your application’s public directory that will allow your user’s images to be served by your application.

php artisan storage:link

API

Jetstream includes first-party integration with Laravel Sanctum. Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token-based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account. These tokens may be granted abilities / permissions which specify which actions the tokens are allowed to perform.

By default, the API token creation panel may be accessed using the “API Tokens” link of the top-right user profile dropdown menu. From this screen, users may create Sanctum API tokens that have various permissions.

Enabling API Support ​

If your application will be offering an API that may be consumed by third-parties, you must enable Jetstream’s API feature. To do so, you should uncomment the relevant entry in the features configuration option of your application’s config/jetstream.php configuration file:

  Features::api(),

In the right side, you can see Team with your name For ex : (‘John’s Team)

If you have  installed Jetstream using the –teams option, your application will be scaffolded to support team creation and management.

Jetstream’s team features allow each registered user to create and belong to multiple teams. By default, every registered user will belong to a “Personal” team. For example, if a user named “John Doe” creates a new account, they will be assigned to a team named “John’ Team”. After registration, the user may rename this team or create additional teams.

Email Verification

Email Verification is used to verify the email address when a new User regiseters. By default Email Verification feature is disabled in Jetstream. To enable this feature open “config/fortify.php” file and uncomment  Features::emailVerification().

Now we need to use MustVerifyEmail interface inside the User model.

In User Model add implements MustVerifyEmail to the User class.

class User extends Authenticatable implements MustVerifyEmail

Now open .env file and enter the mailtrap credentials as shown below :

MAIL_MAILER=smtp
MAIL_HOST=sandbox.smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your mailtrap username
MAIL_PASSWORD=your mailtrap password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"

Now try to open the Dashboard Page, Verify email page. Click on the RESEND VEIFICATION EMAIL button. You will receive a Verification email in your mailtrap inbox, click on the “Verify Email Address” button & it will redirect you to the Dashboard page.

Now whenever a new User registers, the user will get a Verification Email on his email address. He won’t be able to see the dashboard until, he verifies his email.

Open phpMyAdmin & check your database. When the user first registers using his details, in the users table , in the email_verified_at column NULL is inserted.

When the user verifies his email address, a timestamp has been added , which will replace NULL.

Implement Forgot Password

When the user forgots his password, he can reset his password by entering his email address.

Open login page, here you will see “Forgot your password” link. Click on this link and you will see Forgot Password Page. Now enter your Registered email address in the textbox and click on the “Email Password Reset Link” button.

You will receive a Reset Password Notification email. Click on the Reset Password button & you will be redirected to Reset Password Page.

Now enter your new password and confirm this password and click on the Reset Password button, you will be redirected to the login page with success message “Your password has been reset”.

Implement Password Confirmation

While building your application, you may occasionally have actions that should require the user to confirm their password before the action is performed. For example, Jetstream itself requires users to confirm their password before changing their two-factor authentication settings.

Now create a new file called billing.blade.php inside resources/views folder.

Copy the below code & paste inside this billing.blade.php view file.

<x-app-layout>

    <x-slot name="header">

        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">

            {{ __('Billing') }}

        </h2>

    </x-slot>

    <div class="py-12">

        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">

            <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-xl sm:rounded-lg">

                <div class="p-6 lg:p-8 bg-white dark:bg-gray-800 dark:bg-gradient-to-bl dark:from-gray-700/50 dark:via-transparent border-b border-gray-200 dark:border-gray-700">

                    <h1 class="font-medium text-gray-900 dark:text-white">

                       This is a billing page

                    </h1>

                </div>

            </div>

        </div>

    </div>

</x-app-layout>

Now open web.php file and add a route for billing  & add password.confirm middleware to this route after dashboard route:

Route::middleware([
    'auth:sanctum',
    config('jetstream.auth_session'),
    'verified',
    'password.confirm'
])->group(function () {
    Route::get('/billing, function () {
        return view(billing);
    })->name(billing);
});

Now in your browser enter the url localhost:8000/billing

You will be prompted to confirm your password, similar to what you may have seen on other applications like GitHub:

Confirming the password will store a timestamp in the user’s session that lasts for three hours by default so users do not have to enter their password during that period again. You may customize this duration using a new password_timeout configuration option in the auth configuration file(config/auth.php).

In addition, a new password validation rule has been added to the framework. This validation rule may be used to validate that a given password matches the user’s existing password.

Adding wire:navigate for Single Page Application/SPA

Livewire 3 offers a single page application experience via a simple attribute you can add to links in your application: wire:navigate.

We will add wire:navigate to all the links inside navigation menu.

Open navigation-menu.blade.php & add wire:navigate in all the links(except logout) :

  <x-nav-link wire:navigate href="{{ route('dashboard') }}" :active="request()->routeIs('dashboard')">
                        {{ __('Dashboard') }}
                    </x-nav-link>
                    <x-nav-link wire:navigate  href="{{ route('secret') }}" :active="request()->routeIs('secret')">
                        {{ __('Secret') }}
                    </x-nav-link>

Changing Logo

Now lets change the logo inside our App. Go to resources/views/components folder.

Open application-logo.blade.php file and replace the code with below code :

<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-12 h-12 text-amber-500">
    <path stroke-linecap="round" stroke-linejoin="round" d="M15.362 5.214A8.252 8.252 0 0112 21 8.25 8.25 0 016.038 7.048 8.287 8.287 0 009 9.6a8.983 8.983 0 013.361-6.867 8.21 8.21 0 003 2.48z" />
    <path stroke-linecap="round" stroke-linejoin="round" d="M12 18a3.75 3.75 0 00.495-7.467 5.99 5.99 0 00-1.925 3.546 5.974 5.974 0 01-2.133-1A3.75 3.75 0 0012 18z" />
  </svg>

Now open application-mark.blade.php file and replace the code with the below code :

<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-12 h-12 text-amber-500">
    <path stroke-linecap="round" stroke-linejoin="round" d="M15.362 5.214A8.252 8.252 0 0112 21 8.25 8.25 0 016.038 7.048 8.287 8.287 0 009 9.6a8.983 8.983 0 013.361-6.867 8.21 8.21 0 003 2.48z" />
    <path stroke-linecap="round" stroke-linejoin="round" d="M12 18a3.75 3.75 0 00.495-7.467 5.99 5.99 0 00-1.925 3.546 5.974 5.974 0 01-2.133-1A3.75 3.75 0 0012 18z" />
  </svg>

Now open application-card-logo.blade.php file and replace the svg code with the below code :

<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-12 h-12 text-amber-500">
    <path stroke-linecap="round" stroke-linejoin="round" d="M15.362 5.214A8.252 8.252 0 0112 21 8.25 8.25 0 016.038 7.048 8.287 8.287 0 009 9.6a8.983 8.983 0 013.361-6.867 8.21 8.21 0 003 2.48z" />
    <path stroke-linecap="round" stroke-linejoin="round" d="M12 18a3.75 3.75 0 00.495-7.467 5.99 5.99 0 00-1.925 3.546 5.974 5.974 0 01-2.133-1A3.75 3.75 0 0012 18z" />
  </svg>

Now refresh the page and you will see that the logo has been changed.

Conclusion

In this Laravel Authentication using Laravel Jetstream tutorial, we have implemented all the features that are required in Modern Applications.

Leave a Reply