Reputation: 4484
I am building an application that is using a third party authentication database. I have created a custom composer package to "intercept" the POST
request to /login
. Everything is working great - I'm able to get a user object back and save it to my (laravel) database.
I am now at the point where I want to redirect to the home page and do "stuff". I would like to use Laravel's native Auth
as much as possible if I can.
For example, on the home page I am doing this:
$foo = auth()->user()->foo->where('active', 1);
No surprise, since I am not using Laravel's native Auth method, auth()->user()
is returning null
. Once I have my user created/found in my database, is it possible to tie back into Laravel's auth()
methods?
Thank you for any suggestions!
EDIT
Reading the documentation, this looks like the direction I need to go but I'm falling short understanding how to connect/register my custom package (I think)...
EDIT 2
I am going to keep updating this as I feel I make any progress in hopes that it will not only help me, but help others get a better picture of what I am trying to accomplish. Ultimately help others who may be trying to do the same.
I have updated my app/Providers/AuthServiceProviderAuthServiceProvider
as such:
use My\Package\MyThirdPartyServiceProvider;
...
Auth::provider('foo', function ($app, array $config) {
// Return an instance of Illuminate\Contracts\Auth\UserProvider...
return new MyThirdPartyServiceProvider($app->make('foo.connection'));
});
I have also updated my config/auth
file:
'providers' => [
'users' => [
'driver' => 'foo',
'model' => App\User::class,
]
Upvotes: 2
Views: 4046
Reputation: 3835
As you mentioned the documentation suggests implementing a custom user provider. The following steps more or less describe how you'll tackle it in a bit more detail.
php artisan make:provider CustomAuthServiceProvider
boot
method of your service provider you'll have to configure our auth provider (which will be implemented in step 4). public function boot()
{
Auth::provider('custom-auth', function ($app, array $config) {
return new CustomAuthProvider();
});
}
auth.php
configuration to use the serviceprovider we registered in step 2 'providers' => [
'users' => [
'driver' => 'custom-auth',
],
],
CustomAuthProvider
class itself and implement the UserProvider interfaceclass CustomAuthProvider implements UserProvider
{
public function retrieveById($identifier) {
// Retrieve a user by their unique identifier.
}
public function retrieveByToken($identifier, $token) {
// Retrieve a user by their unique identifier and "remember me" token.
}
public function updateRememberToken(Authenticatable $user, $token) {
// Update the "remember me" token for the given user in storage.
}
public function retrieveByCredentials(array $credentials) {
// Retrieve a user by the given credentials.
}
public function validateCredentials(Authenticatable $user, array $credentials) {
// Validate a user against the given credentials.
}
}
Upvotes: 4