New Password Confirmation Flow for Logged In Users in Laravel 6.2

Published on by

New Password Confirmation Flow for Logged In Users in Laravel 6.2 image

Laravel released v6.2 yesterday with a new password confirmation feature that enables you to require a logged-in user to re-enter their password before being allowed access to a route.

This functionality works like the GitHub confirmation screen when you perform sensitive actions. Setting it up is a breeze in Laravel, so let’s take the new feature for a spin so you can see how it works:

Setup

First, let’s create a new Laravel application to work with so you can visualize how this new feature works:

laravel new confirm-app
cd confirm-app
composer require laravel/ui --dev

If you remember, the make:auth command was removed in Laravel 6 and moved to the laravel/ui first-party package. Let’s generate the authorization code for our app:

php artisan ui vue --auth
yarn install
yarn dev

Next, let’s configure an SQLite database (feel free to use whatever driver you want):

touch database/database.sqlite

We’ve created the file that Laravel will look for by default when using the sqlite driver, but you’ll either need to update the .env file with the correct connection and database path:

DB_CONNECTION=sqlite
# ...
# Use the default path of the sqlite driver
# DB_DATABASE=laravel

Next, let’s run migrations and then create a test user:

php artisan migrate

We can create a test user with the console via the factory() :

php artisan tinker
>>> $user = factory(App\User::class)->create([
... 'password' => bcrypt('secret'),
... 'email' => 'admin@example.com'
... ]);

Writing the Controllers

Let’s say that you wanted users to re-authenticate their password before viewing an administration action like adding an SSH key. We would want the user to re-enter their password within the configured window (the default is 3 hours).

We’ll create a fake /settings/ssh/create route where we’ll require the new password.confirm middleware before the user can create a new key:

php artisan make:controller Settings/SSHController

Next, create the controller action create():

namespace App\Http\Controllers\Settings;
 
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
 
class SSHController extends Controller
{
public function create()
{
return view('secret');
}
}

We’ll stub out the secret template, which we put in the root of the views path resources/views/secret.blade.php:

@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<h1>Add a New SSH Key</h1>
<p>This page is only shown after password confirmation.</p>
</div>
</div>
</div>
@endsection

At the time of writing, you need to copy the auth/passwords/confirm.blade.php file to your project. You can get the stub here: ui/confirm.stub. Copy this file and add it to your project in the following path:

resources/views/auth/passwords/confirm.blade.php

Next, we need to define the route, along with the middleware we’ll need for this at the end of the routes/web.php file:

Route::namespace('Settings')
->middleware(['auth'])
->group(function () {
Route::get('/settings/ssh/create', 'SSHController@create')->middleware('password.confirm');
});

Note: typically, you might group all routes requiring authentication together with the auth middleware. For this demo, we’re creating one controller route in the Settings namespace.

With that in place, once you log in, you’ll be redirected to /home. From there, navigate to /settings/ssh/create, and then you’re prompted for your password:

If you followed along with this tutorial, enter secret, submit the form, and then you will be taken to the create view. You can refresh this page without being prompted after confirming the password.

Using the new ddd() Helper, add this to your SSHController::create() method to visualize the auth.password_confirmed_at session value that determines the next time you’ll be prompted:

public function create()
{
ddd(session('auth'));
return view('secret');
}

This value was the timestamp when the password was last confirmed. By default, the middleware will not re-prompt for three hours. You can control how long before the user should confirm the password again with the config('auth.password_timeout') value located in config/auth.php as of Release v6.2.0.

Learn More

First of all, thanks Dries Vints for this wonderful new feature! Check out Pull Request #5129 for the implementation details. Any new Laravel applications created with Laravel 6.2 include this new middleware!

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Filed in:
Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3 image

Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3

Read article