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!

William Shakespeare
Release: 2025-02-10 12:27:14
Original
537 people have browsed it

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.

Modify login link

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template