Sunday, October 23, 2016

Api authorization with Passport in Laravel 5.3

This tutorial is basically an environment set up to understand how Passport works in Laravel 5.3.

Passport is a way to manage authentication for accessing API in Laravel. It is very easy to implement and user do not need to concern about background activities   of Oauth.

To implement Passport in local environment , we need two projects. One will be working as server, which authenticate a user and another one will be working as client, which will request for resource via API.


so i am using two laravel 5.3 instances as server and client.

Server is running on localhost:8000
Client is running on localhost:9000

Here is the instructions that must be followed to setup oAuth server on our Server(localhost:8000)

1. composer require laravel/passport

Register PassportServiceProvider in providers array on app.php file

2. Laravel\Passport\PassportServiceProvider::class,

Migrate tables related to Passport.

3. php artisan migrate

Create Encryption key to generate secure access key

4. php artisan passport:install

Add HasApiTokens traits is used in User model, which will provide some helper functions to play with access tokens.

5. <?php

namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}

Now in AuthSericeProvider's boot function add following codes to automatically set up required routes related to passport

6.  public function boot()
    {
        $this->registerPolicies();

        Passport::routes();
    }

Now in config/auth.php file set Passport as API driver


7. 'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],

Now run following code to publish vue components related to Passport.


8. php artisan vendor:publish --tag=passport-components
Now add following code in app.js file


9. Vue.component(
    'passport-clients',
    require('./components/passport/Clients.vue')
);

Vue.component(
    'passport-authorized-clients',
    require('./components/passport/AuthorizedClients.vue')
);

Vue.component(
    'passport-personal-access-tokens',
    require('./components/passport/PersonalAccessTokens.vue')
);

Now we have to compile this by running following code

10.
   gulp watch



Now add following lines in the view page in order to give access to admin to create client, personal access token.


11.
<passport-clients></passport-clients>
<passport-authorized-clients></passport-authorized-clients>
<passport-personal-access-tokens></passport-personal-access-tokens>
Now our server configuration done. Now we'll create new client in order to give access.

12.


Now we'll setup our client

In Client's web.php file add following code :

1.
 use Illuminate\Http\Request;

Route::get('/', function () {
    $query = http_build_query([
        'client_id' => 12,        'redirect_uri' => 'http://localhost:9000/callback',        'response_type' => 'code',        'scope' => '',    ]);
    return redirect('http://localhost:8000/oauth/authorize?'.$query);});
Route::get('/callback', function (Request $request) {

    $http = new GuzzleHttp\Client;
    $response = $http->post('http://localhost:8000/oauth/token', [
        'form_params' => [
            'grant_type' => 'authorization_code',            'client_id' => 12,            'client_secret' => 'rfkixBY5v3SwnqwRM570yKHfgQMRNyNDd1WgOxWP',            'redirect_uri' => 'http://localhost:9000/callback',            'code' => $request->code,        ],    ]);
    return json_decode((string) $response->getBody(),true);    

});

So our basic setup done. Now if we'll try to access localhost:9000 we'll be redirect to following page:

2.


Now if we authorize we'll see access token as follow

3.

Now our system is working fine. If we go to localhost:8000 and refresh our browser , we'll see following view

4.


We can also create personal access token. To generate personal access token we need to create a Password grant client using following command:

1 . php artisan passport:client --password 

Now in our server application we can create personal access token.



4 comments:

  1. Hi, How can I implement password grant client with javascript?

    ReplyDelete
  2. do i need to make all that on a fresh laravel project?
    could you please complete this with a clear example that includes:
    login from a third party app like C#.
    make any request using the authorized user.

    ReplyDelete
  3. Thank you for this hands-on explanations.
    Would you plz explain how to proceed next after client getting the access token?How to redirect the client to landing page?

    ReplyDelete
  4. You,just show the create personal access token. How can use it in web.php ??

    ReplyDelete