Implementing Google Login With JWT in Laravel 7.x for RESTful API Authentication
It’s become common now implementing RESTful API since server can communicate with various devices to communicate each other. Using 3rd party login is not the exception. Nowadays it’s pretty common the application support login by Google for authentication either from mobile device, PC and so on.
In this case we have 2 problems:
- How we authenticate access without hold any session value which is called as statelessness in RESTful API?
- How to generate JWT token using passport without using request to Passport OAuth?
This short article will introduce you on how to implement it easily. First of all I assume you understand and able to created a basic Laravel 7 project.
I myself for this article create a Laravel project named rest-stateless (feel free to use this approach or another approach if you like to do so to organize your working directory structure). Next we need to install Laravel Passport, we’ll use JWT Token from this package (make sure you’ve adjusted .env properly especially before running migrate command):
$ composer require laravel/passport
$ php artisan migrate
$ php artisan passport:install
Next modified User model to be like this:
then we create AuthController for implementing login by Google:
We need to create a Traits named PassportToken. Create a directory named Traits inside App/Http directory followed by create a file named PassportToken.php with code as follow:
Last let’s add route to do login by google by adding this code at routes/api.php
Route::POST('/login_google', 'AuthController@loginByGoogle');
Cool, we have created a method to authenticate but how to test it? let’s go to https://developers.google.com/oauthplayground/ and we’re going to create a valid goole token to be tested in our application. At “input your own scopes” let’s add this:
https://www.googleapis.com/auth/userinfo.email
So maybe in the future you can grab email when made request. For further detail about scope you can visit this page
click Authorize APIs and Sign in using your own Google account followed by clicking Exchange authorization code for tokens. We got something like this:
now we can copy access token and test our application using curl as follow (if you’re running your Laravel using php artisan serve at port 8000):
$ curl -X POST \
http://localhost:8000/api/login_google/ \
-H 'Content-Type: application/json' \
-d '{
"token": "__PASTE YOUR ACCESS TOKEN HERE__"
}'
Congratulation we have accomplished authentication from google to our RESTful API in Laravel 7. Repository for this project can be accessed here.