DecryptException error – Mac invalid

Developing locally I got into issues with Laravel Fortify 2 factor authentication. I often got an error caching issue related to the two factor authentication keys in tandem with the APP_KEY:

Illuminate\Contracts\Encryption\DecryptException
PHP 8.2.15
9.52.16
The MAC is invalid.

I did set cache driver to null and CACHE_DRIVER=null then also did php artisan:config:clear besides composer dump-autoload --no-dev but then I got

Class "Barryvdh\Debugbar\ServiceProvider" not found

Reinstalled Debug Bar using composer require --dev barryvdh/laravel-debugbar . Then I did a php artisan config:clear again and removed cookies and local storage. Still seeing the error after adding the two factor authentication code.

Realized I needed to remove/replae the two factor secret key and recovery codes as those were encrypted using a different key, but fortunately found the old API Key and that worked.

Two Factor Codes Update Command

A command to update the key and recovery codes for a user could be something like


namespace App\Console\Commands;
use Illuminate\Support\Facades\DB;
use Laravel\Fortify\Actions\UpdateTwoFactorAuthentication;

class UpdateTwoFactorAuth extends Command
{
    protected $signature = 'update:2fa {userId}'; // Add the user ID as an
option

    protected $description = 'Update two-factor authentication for a user';

    public function handle()
    {
        $userId = $this->argument('userId');

        if (!$user = User::find($userId)) {
            $this->error('User not found.');
            return;
        }

        if (!$user->hasTwoFactorAuth()) {
            $this->warn('User does not have two-factor authentication enabled. Cannot update.');
            return;
        }

        $provider = app(UpdateTwoFactorAuthentication::class);
        $secretKey = $provider->generateSecretKey();
        $recoveryCodes = json_encode(Collection::times(8, function () {
            return RecoveryCode::generate();
        })->all());

        DB::table('users')
             ->where('id', $userId)
             ->update([
                 'two_factor_secret' => encrypt($secretKey),
                 'two_factor_recovery_codes' => encrypt($recoveryCodes),
             ]);

        $this->info('Two-factor authentication updated for the user!');
    }
}

Now, when you run this command from the terminal, you can specify the user
ID as an argument. For example:

php artisan update:2fa 1
Jasper Frumau

Jasper has been working with web frameworks and applications such as Laravel, Magento and his favorite CMS WordPress including Roots Trellis and Sage for more than a decade. He helps customers with web design and online marketing. Services provided are web design, ecommerce, SEO, content marketing. When Jasper is not coding, marketing a website, reading about the web or dreaming the internet of things he plays with his son, travels or run a few blocks.