Let's Kill the Password! Magic Login Links to the Rescue!
Feb 10, 2025 pm 12:27 PMSay 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.
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.
The login process without password is as follows:
- Users access login page;
- Enter email address and confirm;
- The system sends a login link to the email address;
- After clicking on the link, the user is redirected back to the application and logged in;
- 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.*
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>
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.*
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>
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
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
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="http://www.miracleart.cn/link/9964364bfd2b38643a0b41b981c01f60'/login/magiclink') }}">Login</a></li> <li><a href="http://www.miracleart.cn/link/9964364bfd2b38643a0b41b981c01f60'/register') }}">Register</a></li> [...]
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); } [...]
Let's update the MagicLoginController to include the show action:
app/Http/Controllers/Auth/MagicLoginController.php
php artisan make:controller Auth\MagicLoginController
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');
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'); } [...] }
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:
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. UseMail::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, useAuth::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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas
