DEV Community

loading...
Cover image for Create API Rest with Laravel 7.X Passport Authentication And Implement Refresh Token (Part 3)

Create API Rest with Laravel 7.X Passport Authentication And Implement Refresh Token (Part 3)

Mohammad Reza
Software Engineer at Cafe Bazaar
・1 min read

In this part we want to implement the refresh token

Step 1. Change api.php

we need to add refresh token route like this

<?php

use Illuminate\Support\Facades\Route;

Route::post('login', 'UserController@login');
Route::post('register', 'UserController@register');
Route::post('refreshtoken', 'UserController@refreshToken');

Route::get('/unauthorized', 'UserController@unauthorized');
Route::group(['middleware' => ['CheckClientCredentials','auth:api']], function() {
    Route::post('logout', 'UserController@logout');
    Route::post('details', 'UserController@details');
});
Enter fullscreen mode Exit fullscreen mode

Step 2. Add refreshToken Function in UserController.php

We send request to "oauth/token" with Refreshtoken header and give access token and a new refresh token

...
    public function refreshToken(Request $request) { 
        $refresh_token = $request->header('Refreshtoken');
        $oClient = OClient::where('password_client', 1)->first();
        $http = new Client;

        try {
            $response = $http->request('POST', 'http://mylemp-nginx/oauth/token', [
                'form_params' => [
                    'grant_type' => 'refresh_token',
                    'refresh_token' => $refresh_token,
                    'client_id' => $oClient->id,
                    'client_secret' => $oClient->secret,
                    'scope' => '*',
                ],
            ]);
            return json_decode((string) $response->getBody(), true);
        } catch (Exception $e) {
            return response()->json("unauthorized", 401); 
        }
    }
...
Enter fullscreen mode Exit fullscreen mode

Like this
Alt Text

now you have all things that you need for api auth :)

if you have question you can ask it here :)

share it with your friends if you like it

Discussion (3)

Collapse
mrzer0 profile image
Yan Naing (ရန်နိင်)

Hi Mohammad,

It might not relate with your tutorial. I would like to know the difference between Sanctum and Passport. Is Sanctum alone sufficient for RESP api? I mean not only own SPA frontend but also for other third-party application which will use my backend REST api.

Collapse
ericsts profile image
Eric Luiz dos Santos

Hi
Nice tutorial !
What is this URL : mylemp-nginx/oauth/token ??

Thanks

Collapse
remlinenl profile image
R. Cloeck

its the url he sends the oauth request to
you can replace it to

$response = $http->request('POST', route('passport.token'), [