Making WordPress passwords work in Laravel

When you are exporting WordPress users to a Laravel Application, you’ll notice that the hashed password from WordPress will not authenticate in Laravel.

Quick note: an updated version of this post can be found on my personal site.

Now instead of your users having to reset the password, you can do the following;

I) Install the ‘Laravel WP Password’ package and follow the installation instructions.

II) Create an ‘LogFailedAuthenticationAttemp.php’ event listener (‘app/Listeners) and pasted the following code in that file;

<?php


namespace App\Listeners;


use Illuminate\Auth\Events\Failed;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\User as User;
use MikeMcLin\WpPassword\Facades\WpPassword;
use Auth;
use Hash;


class LogFailedAuthenticationAttempt
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }


    /**
     * Handle the event.
     *
     * @param  Failed  $event
     * @return void
     */
    public function handle(Failed $event)
    {
      $user = User::where('email',$event->credentials['email'])->first();


      if ( $user ) {
        if ( WpPassword::check($event->credentials['password'], $user->password ) ) {
          Auth::login($user);


          $user->password = Hash::make($event->credentials['password']);
          $user->save();


        }
      }
    }
}

This code will hook on a failed login attempt and check if a WordPress password variant does succeed. If it does, it will log the user in and also update the user password to a Laravel hashed variant. If not, it does nothing.

III) Finally, in the EventServiceProvider.php (app/Providers)file add the following under $listen;
‘Illuminate\Auth\Events\Failed’ => [
‘App\Listeners\LogFailedAuthenticationAttempt’,
],

That’s it. It took me some time to figure out and I thought it might be useful for someone else too.

Related Articles

Comments 0