Asudahlah.com

Programming, tutorials, mechatronics, operating systems, and other tech stuff

Tutorial: Use Google Authentication (or other OAuth Service) in Laravel 8 project

No comments

In this tutorial we will use Google Authentication (or any other OAuth service like facebook, twitter, etc) as an alternative login option for your laravel application. As you can see in many apps out there, user registration is optional because user can just click "Sign in with google" or something like that.

How does it work

When new user clicked the "Sign in with google" button, the application will send a request to google for user info. Google then provide the user info along with a unique ID, then the app register that info in the database because it doesn't exist yet. So now the user is a registered user.

Next time, when the user login they only need to do the same thing. The app then request the user info again, got the ID, and then check the database. Because the ID exist, the user then logged in by the system.

What you need

Because we use third party service here, we need to authorize our app to request user info. Visit google developer console. Make a project then you will got something like this.


Then go to "OAuth Consent Screen" menu, choose "External" then Create.

You only need to fill "Application Name" field for now. Then save.

Go to "Credential" menu, then create a new OAuth Client ID.
Fill out the name and the Redirect URL. In my case, i use http://localhost/gemacms/public/auth/callback/google because i hosted my app locally.
Click "save" and you will get a ClientID and Secret Key.

Integrate OAuth to laravel project

Add fields to your user table namely:
socialite_id,email, avatar(optional).

In your laravel project, install socialite library.
composer require laravel/socialite
Then open your .env, and put :
GOOGLE_CLIENT_ID=paste your client ID here GOOGLE_CLIENT_SECRET=paste your secret key here GOOGLE_CLIENT_CALLBACK=http://localhost/gemacms/public/auth/callback/google(adjust to your setting)


Then in your config/services.php, add:
    'google' => [
        'client_id' => env('GOOGLE_CLIENT_ID'),
        'client_secret' => env('GOOGLE_CLIENT_SECRET'),
        'redirect' => env('GOOGLE_CLIENT_CALLBACK'),
    ],

Add these 2 route in your route/web.php
Route::get('auth/{driver}''LoginController@oauth_login');
Route::get('auth/callback/{driver}''LoginController@oauth_callback');
First route is for when the user click the "Sign in with..." button. The socialite library will then redirect to the second route when the auth is success.

Now create the LoginController controller and create 2 method inside it:
    public function oauth_login(Request $request, $driver){
        return Socialite::driver($driver)->redirect();
    }
    public function oauth_callback(Request $request, $driver){
        $oauthUser = Socialite::driver($driver)->user();
        $user = User::where('socialite_id'$oauthUser->getId())->first();
        if ($user) {
            Auth::loginUsingId($user->id_users);
            return redirect('admin/dashboard');
        } else {
            $newUser = User::create([
                'username' => $oauthUser->getEmail(),
                'roles_id' => 1,
                'name' => $oauthUser->getName(),
                'email' => $oauthUser->getEmail(),
                'socialite_id'=> $oauthUser->getId(),
                'avatar'=> $oauthUser->getAvatar(),
                'password' => md5($oauthUser->token),
            ]);
            Auth::login($newUser);
            return redirect('admin/dashboard');
        }
    }

When the user clicked the "Sign in with..." url, it will load the oauth_login method. This will load the socialite library with the specified driver (google in this case), then redirect to the url as provided in the GOOGLE_CLIENT_CALLBACK in .env (in my case, it's http://localhost/gemacms/public/auth/callback/google) . Which is basically calls the oauth_callback method with "google" as parameter.

Then inside the oauth_callback we call Socialite::driver($driver)->user() which will provide us with these info (copied from the docs):
// OAuth Two Providers
$user->token;
$user->refreshToken; // not always provided
$user->expiresIn;

// OAuth One Providers
$user->token;
$user->tokenSecret;

// All Providers
$user->getId();
$user->getNickname();
$user->getName();
$user->getEmail();
$user->getAvatar();

With getId() we can get the unique user ID from google. With this ID, we can match it with the one we had in the database. If it doesn't exist yet, we create the user with info provided above. And if done or the user is already exist, we logged in the user.

Keep in mind that password is not really required in this method.

Then in your login page, add a link to auth/google :
<a href="{{ url('/auth/google') }}" class="btn btn-danger btn-block">{{ __('Sign in with Google'}}</a>

That's it.

No comments :

Post a Comment