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.



Related Posts:

  • Add Cron jobs to run scheduling jobs for Laravel Developer on Ubuntu I have faced a lot of problems to run schedule jobs in Laravel. I am using Ubuntu 14.04 and i spent a lot of time to make it work. Here i wrote down the basic procedure that i followed. First  To run scheduled job… Read More
  • Laravel 5.2 using queue to send email To sent email after desired number of second, first change the .env file as follow. First provide database credential set QUEUE_DRIVER=sync to QUEUE_DRIVER=database Normally , QUEUE_DRIVER=sync tries to sent email immedi… Read More
  • Laravel 5.2 queuing Event listeners First , we need to create Event and to listen event, we also have to create listener. To do this , laravel provides us several ways. The easiest way to create event and corresponding listener we can use this command php ar… Read More
  • Create Your own command on Laravel 5.2 In Laravel application , when you try this command php artisan you would see lots of command for laravel application. So if you want to create your own command, laravel provide you very easy way to do this. Here is the … Read More
  • Laravel 5.2 Implicit model binding In Laravel 5.2 new feature called implicit model binding added. Which can be implement efficiently and in a very easy manner. Here how its done : In your routes.php file create a new route Route::get('user',function(){}); … Read More

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