Tips on extending the Laravel 5 Authentication system
by corbosmanTips on extending the Laravel 5 Authentication system
I often see questions posted or asked on chat on how to extend the laravel authentication system. The laravel 5.1 docs do a good job explaining the basics on how to do this, but it isn't complete. Here are some tips to help you make the most of it.
Replacing Guard
- A common question asked is if you can extend the Laravel Guard class. The Guard class is the class that you normally interact with if you say Auth::attempt() or Auth::user(). The docs don't mention this, but you can actually use the same method to replace the Guard class as you use to replace the UserProvider. Here is an example service provider to do this.
<?php
namespace App\Providers;
use Auth;
use App\Extensions\MyGuard;
use App\Extensions\MyUserProvider;
use Illuminate\Support\ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
Auth::extend('riak', function($app) {
return new MyGuard(
new MyUserProvider($app['myprovider.connection']),
$app->make('session.store')
);
});
}
/**
* Register bindings in the container.
*
* @return void
*/
public function register()
{
//
}
}
This is possible because the Laravel AuthManager actually checks if you're providing a UserProvider or a Guard. If you provide just the UserProvider like the example in the docs, it will add the Guard for you. Here is the actual code from laravel responsible for this.
protected function callCustomCreator($driver)
{
$custom = parent::callCustomCreator($driver);
if ($custom instanceof GuardContract) {
return $custom;
}
return new Guard($custom, $this->app['session.store']);
}
Remember though, your MyGuard class needs to implement the Guard Contract. This brings me to tip 2.
Replacing one or two methods
- You don't have to write the whole class. Often you simply want to change one or two methods in the class. In that case, simply extend the Guard class in your MyGuard class. Here's an example that simply replaces the check() method.
<?php namespace App\Extensions;
use Illuminate\Auth\Guard;
class MyGuard extends Guard
{
public function check()
{
....
}
}
Of course the same goes for the UserProvider. If you just want to replace one method, lets say validateCredentials, you can simply extend one of the existing UserProviders.
<?php namespace App\Extensions;
use Illuminate\Auth\EloquentUserProvider;
class MyUserProvider extends EloquentUserProvider
{
public function validateCredentials(UserInterface $user, array $credentials)
{
....
}
}