In this fast tutorial, we will create the easiest Passwordless Login in Laravel, using Signed URLs.
Signed URLs are available in Laravel since version 5.6, but in my experience they aren’t known enough.
📌 We assume you have the login view with a form with only the email field.
We need just 2 routes, that is…
Route 1: Post user email
This route:
receive the user email
create a Signed URL
and send it to user via email (or other channel).
Route::post(‘/passwordless/login’, function(Request $request) {
// please, move me to a Controller 😉
$request->validate([
’email’ => ‘required|email’
]);
$user = User::query()
->where(’email’, $request->email)
->first();
if ($user) {
$passwordlessUrl = URL::temporarySignedRoute(
‘passwordless.login’,
now()->addMinutes(10),
[‘user’ => $user->id]
);
// notify user via email or other channel…
$user->notify(new PasswordlessNotification($passwordlessUrl));
}
// else… we send always a success message to avoid any “info extraction”
return back()->with(‘success’, ‘You have an email!’);
});
Route 2: check signature and login
Here, we have the route that login the user:
it receive the user id (the model is loaded automatically by Model Binding)
it validate signature (🎯 it’s really important! 😎)
and finally login the user.
Route::get(‘/passwordless/login/{user}’, function(Request $request, User $user) {
// please, move me to a Controller 😉
if (! $request->hasValidSignature()) {
abort(401);
}
Auth::login($user);
return redirect(‘/’);
})->name(‘passwordless.login’);
…and that’s it!
The PasswordlessNotification class
In the Route 1, we assumed that you have a PasswordNotification class.
For simply do that:
And then:
class PasswordlessNotification extends Notification
{
use Queueable;
public function __construct(
public string $passwordlessUrl
) {}
public function via(object $notifiable): array
{
return [‘mail’];
}
public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)
->subject(‘Your magic link to login’)
->line(“Hi {$notifiable->firstname}“)
->line(‘you can login by the link below:’)
->action(‘Login’, $this->passwordlessUrl)
->line(‘Thank you for using our application!’);
}
}
✸ Enjoy your coding!
If you liked this post, don’t forget to add your Follow to my profile!
If you want to preview my content, Subscrive to my Newsletter!