Table of Contents
Core Points
Migration
Modify login link
Create magic login controllers, views and routes
Home Backend Development PHP Tutorial Let's Kill the Password! Magic Login Links to the Rescue!

Let's Kill the Password! Magic Login Links to the Rescue!

Feb 10, 2025 pm 12:27 PM

Say goodbye to password troubles and embrace safe and convenient password-free login! This article will guide you how to implement a one-time link-based password-free login system in Laravel applications to improve security and simplify user experience.

Let's Kill the Password! Magic Login Links to the Rescue!

This article was reviewed by Younes Rafie and Wern Ancheta. Thanks to all the peer reviewers at SitePoint for getting SitePoint content to its best!


Identity authentication technology continues to evolve, from traditional mailbox-password combinations, to social login, to today's passwordless login (more precisely, "email-only" login). The passwordless login system verifies identity by sending a login link to the user's email.

Let's Kill the Password! Magic Login Links to the Rescue!

The login process without password is as follows:

  1. Users access login page;
  2. Enter email address and confirm;
  3. The system sends a login link to the email address;
  4. After clicking on the link, the user is redirected back to the application and logged in;
  5. The link is invalid.

If you forget your application password but remember to register your email, this method is very useful. This technology is also adopted by applications such as Slack. This tutorial will demonstrate how to implement this system in a Laravel application. See the full code here.

Core Points

  • Abandon passwords: Use "magic login link" based on a one-time URL to achieve simple and secure password-free authentication.
  • User-friendly settings: User-friendly settings:
  • Use predefined commands and a small number of modifications to easily implement this system in Laravel applications.
  • Enhanced Security:
  • Magic login link eliminates common vulnerabilities in traditional crypto systems such as weak passwords and phishing attacks.
  • Flexibility and control:
  • Users can still choose to log in with traditional passwords, taking into account flexibility and security.
  • Efficient token management:
  • The system automatically handles token expiration and verification to ensure that the token is used correctly and will not be valid for a long time.

Create an app

First, create a new Laravel application. This tutorial uses Laravel 5.2:
composer create-project laravel/laravel passwordless-laravel 5.2.*
Copy after login
Copy after login

If you already have a Laravel project with user and password, don't worry, we won't modify the normal authentication process, but add a layer on top of it. Users can still choose to log in with their password.

Database settings

Before running the migration, you need to set up a MySQL database.

Open the .env file in the root directory and enter the host name, user name and database name:
<code>[...]
DB_CONNECTION=mysql
DB_HOST=localhost
DB_DATABASE=passwordless-app
DB_USERNAME=username
DB_PASSWORD=
[...]</code>
Copy after login
Copy after login

If you are using Homestead Improved box, the database/username/password combination is homestead, homestead, secret.

Build authentication

Laravel version 5.2 introduces a great feature: add a prefabricated authentication layer with just one command. Let's do this: <🎜>
composer create-project laravel/laravel passwordless-laravel 5.2.*
Copy after login
Copy after login

This command builds everything you need for authentication, namely views, controllers, and routes.

Migration

In the database/migrations directory, you can see that the generated Laravel application contains the migration files that create users tables and password_resets tables.

We will not modify anything because we still want the app to have a normal authentication process.

To create a table, run:

<code>[...]
DB_CONNECTION=mysql
DB_HOST=localhost
DB_DATABASE=passwordless-app
DB_USERNAME=username
DB_PASSWORD=
[...]</code>
Copy after login
Copy after login

The app is now available and users should be able to register and log in using the links in the navigation bar.

Next, we will modify the login link to redirect it to a custom login view where the user will submit only the email address without a password.

Navigate to resources/views/layouts/app.blade.php. There you can find the navigation bar section. Change the line containing the login link (below the conditional statement that checks whether the user has logged out) to:

resources/views/layouts/app.blade.php

php artisan make:auth
Copy after login

When unlogged users try to access protected routes, they should be taken to a new custom login view, rather than the normal login view. This behavior is specified in the authenticate middleware. We need to adjust it:

app/Http/Middleware/Authenticate.php

php artisan migrate
Copy after login

Note that in the else block we have changed the redirect to point to login/magiclink, not the normal login.

Create magic login controllers, views and routes

The next step is to create a MagicLoginController in the Auth folder:

[...]
@if (Auth::guest())
<li><a href="https://www.php.cn/link/9964364bfd2b38643a0b41b981c01f60'/login/magiclink') }}">Login</a></li>
<li><a href="https://www.php.cn/link/9964364bfd2b38643a0b41b981c01f60'/register') }}">Register</a></li>
[...]
Copy after login

Then there is the route that displays the custom login page:

app/Http/routes.php

class Authenticate
{
[...]
public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->guest()) {
        if ($request->ajax() || $request->wantsJson()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('login/magiclink');
        }
    }

    return $next($request);
}
[...]
Copy after login

Let's update the MagicLoginController to include the show action:

app/Http/Controllers/Auth/MagicLoginController.php

php artisan make:controller Auth\MagicLoginController
Copy after login

For the new login view, we will borrow the normal login view, but delete the password field. We also changed the form's post URL to point to /login/magiclink.

Let's create a magic folder in the views/auth folder to save this new view:

[...]
Route::get('/login/magiclink', 'Auth\MagicLoginController@show');
Copy after login

Let's update the newly created view to:

resources/views/auth/magic/login.blade.php

class MagicLoginController extends Controller
{
    [...]
    public function show()
    {
        return view('auth.magic.login');
    }
    [...]
}
Copy after login

We will retain the option to log in with password, as users may still choose to log in with password. So if the user clicks on login in the navigation bar, they will see the login view as shown below:

Let's Kill the Password! Magic Login Links to the Rescue!

Due to space limitations, the rest of the parts cannot be fully expanded, but the basic ideas are as follows:

  • Generate and associate tokens: Create a route and controller method to handle the submission of login forms, verify the email address, generate a token for the user, and associate the token with the user. Use str_random() to generate a random token and store it in the database.
  • Send token mail: Add method to the UserToken model to send emails containing login links using Laravel's mail feature. The link should contain the token, email address and remember my value. Use Mail::raw() to send plain text messages, or create a mail view to enhance the appearance of the message.
  • Token Verification and Authentication: Create a route and controller method to handle clicking on the login link. Use the routing model binding to get the token, verify that the token has expired and belongs to the submitted email address. Use the Carbon library to check the expiration time of the token. After the verification is successful, use Auth::login() to log in to the user and delete the used token.

Through the above steps, you can implement a safe and reliable password-free login system in the Laravel application, providing users with a more convenient and safe login experience. Remember to adjust the token expiration time and other settings according to your actual needs. For complete code and more detailed steps, please refer to the complete code link you provided.

The above is the detailed content of Let's Kill the Password! Magic Login Links to the Rescue!. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles