Laravel 5 authenticates users through an external API

I would like to know if it is possible to extend the built-in authentication to use an external API for user authentication? I am new to Laravel, so I will be grateful for your help. I am making a custom application in Laravel 5.2 for my client, but I do not have direct access to their database server, and I can only call their API to get user information.

Thanks.

+4
source share
1 answer

If I understand correctly, do you want to register users from an API, for example, facebook, twitter or github? If so, you need to use the laravel package named Socialite, here is the link to download and use it: https://github.com/laravel/socialite

run the following command:

composer require laravel/socialite

Then you need to tell laravel that you want to use this package, so you need to add it to config / app.php:

'providers' => [
// Other service providers...

Laravel\Socialite\SocialiteServiceProvider::class,
],

and these are aliases:

'Socialite' => Laravel\Socialite\Facades\Socialite::class,

Basically, you will need to create an application on the developers site, I'll take facebook for this example. You need to go to this site: https://developers.facebook.com/ , create an account, and you will receive the URL of your application and the secret key. You will use it in the .env and config / services files.

In the config / services file, add this after the bar:

'facebook' => [
    'client_id' => env('FACEBOOK_ID'),
    'client_secret' => env('FACEBOOK_SECRET'),
    'redirect' => env('FACEBOOK_URL'),
],

.ENV :

FACEBOOK_ID=*your facebook id*
FACEBOOK_SECRET=*your facebook secret*
FACEBOOK_URL=http://yourwebsite.com/callback

auth, - SocialAuthController :

public function redirect()
{
    return Socialite::driver('facebook')->redirect();
}

public function callback() {
    $user = $this->findOrCreateFbUser(Socialite::driver('facebook')->user());


    session([
        'user' => $user
    ]);
    return redirect()->route('/');

}

public function logout() {

    session()->forget('user');

    return redirect()->route('home');
}

protected function findOrCreateFbUser($fbUser) {
    // the data you want to get from facebook
    $fbData = [
        'facebook_id'   => $fbUser->id,
        'avatar'        => $fbUser->avatar,
        'username'      => $fbUser->name,
        'email'         => $fbUser->email,
    ];

    $user = \App\User::where('facebook_id', $fbData['facebook_id'])->first();

    if(!$user) $user = \App\User::create($fbData);

    $user->update([
        'avatar' => $fbUser->avatar,
        'username' => $fbUser->name,
        'email' => $fbUser->email
    ]);


    return $user;
}

, facebook_id . User.php:

protected $fillable = [
    'facebook_id',
    'username',
    'email',
    'avatar'

];

, , api, Laravel, stackoverflowquestion, :) -, , .

- Laracasts, , !

+1

Source: https://habr.com/ru/post/1623771/


All Articles