X
    Categories: Laravel

Laravel Token Based Authentication

Laravel token based Authentication

To work with laravel Token based authentication you should installed Dingo and JWT.

How to install Dingo :  http://www.17educations.com/laravel/laravel-5-1-dingo-api/

How to install JWT : http://www.17educations.com/laravel/laravel-5-1-jwt-and-dingo-api/

Here we are going to see how to install oauth2 package and Token based authentication.

Step 1 : Add oauth2 pacjage in composer.json and run composer update

"require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
        "barryvdh/laravel-debugbar": "~2.2",
        "anahkiasen/former": "~4.0",
        "phpdocumentor/reflection": "3.x@dev",
        "dingo/api": "1.0.x@dev",
        "lucadegasperi/oauth2-server-laravel": "5.1.*"
    }

Step 2 : Add Provider in config/app.php

// Oauth 2 Service Provider
LucaDegasperi\OAuth2Server\Storage\FluentStorageServiceProvider::class,
LucaDegasperi\OAuth2Server\OAuth2ServerServiceProvider::class,

Add below lines in Alias Array,

'Authorizer' => LucaDegasperi\OAuth2Server\Facades\Authorizer::class,

 Step 3 : Add $middleware and $routeMiddleware in your app/Http/Kernal.php

<?php
    protected $middleware = [
        //Add bottom lines to your $middleware array.
        \LucaDegasperi\OAuth2Server\Middleware\OAuthExceptionHandlerMiddleware::class,
    ];
    //
    protected $routeMiddleware = [
        //Add bottom lines to your $routeMiddleware array.
        'oauth' => \LucaDegasperi\OAuth2Server\Middleware\OAuthMiddleware::class,
        'oauth-user' => \LucaDegasperi\OAuth2Server\Middleware\OAuthUserOwnerMiddleware::class,
        'oauth-client' => \LucaDegasperi\OAuth2Server\Middleware\OAuthClientOwnerMiddleware::class,
        'check-authorization-params' => \LucaDegasperi\OAuth2Server\Middleware\CheckAuthCodeRequestMiddleware::class,
    ];

 Step 4 : Publish vendor by running the below command.

php artisan vendor:publish

Result Will be :

Copied File [/vendor/lucadegasperi/oauth2-server-laravel/config/oauth2.php] To [/config/oauth2.php]
Copied Directory [/vendor/lucadegasperi/oauth2-server-laravel/database/migrations] To [/database/migrations]
Copied File [/vendor/anahkiasen/former/src/config/former.php] To [/config/former.php]
Publishing complete for tag []!

It will create outh2.php file under config folder.
Will create migrations file under database folder

Step 5 : Run migration to install oauth table

php artisan migrate

Result :
Migrated: 2014_04_24_110151_create_oauth_scopes_table
Migrated: 2014_04_24_110304_create_oauth_grants_table
Migrated: 2014_04_24_110403_create_oauth_grant_scopes_table
Migrated: 2014_04_24_110459_create_oauth_clients_table
Migrated: 2014_04_24_110557_create_oauth_client_endpoints_table
Migrated: 2014_04_24_110705_create_oauth_client_scopes_table
Migrated: 2014_04_24_110817_create_oauth_client_grants_table
Migrated: 2014_04_24_111002_create_oauth_sessions_table
Migrated: 2014_04_24_111109_create_oauth_session_scopes_table
Migrated: 2014_04_24_111254_create_oauth_auth_codes_table
Migrated: 2014_04_24_111403_create_oauth_auth_code_scopes_table
Migrated: 2014_04_24_111518_create_oauth_access_tokens_table
Migrated: 2014_04_24_111657_create_oauth_access_token_scopes_table
Migrated: 2014_04_24_111810_create_oauth_refresh_tokens_table

Step 6 : Create OAuth Service provider

Run below Command to create Service Provider

php artisan make:provider OAuthServiceProvider

It will create OAuthServiceProvider.php file in app/Providers/OAuthServiceProvider.php 


Change your app/Providers/OAuthServiceProvider.php file like below

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use App\User;
use Dingo\Api\Auth\Auth;
use Dingo\Api\Auth\Provider\OAuth2;

class OAuthServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
       public function boot()
        {
            $this->app[Auth::class]->extend('oauth', function ($app) {
                $provider = new OAuth2($app['oauth2-server.authorizer']->getChecker());

                $provider->setUserResolver(function ($id) {
                    // Logic to return a user by their ID.
                    return User::findOrFail($id);
                });

                $provider->setClientResolver(function ($id) {
                    // Logic to return a client by their ID.
                });

                return $provider;
            });
        }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

 Step 7 : Add your service Provider in config/app.php provider array.

App\Providers\OAuthServiceProvider::class,

and Run composer dump-autoload in your terminal to autoload service provider.

Step 8 :  Add grant_type with in the array with in the oauth2.php

'grant_types' => [
        'password' => [
             'class' => 'League\OAuth2\Server\Grant\PasswordGrant',
             'access_token_ttl' => 604800,
             
             // the code to run in order to verify the user's identity
             'callback' => 'App\Verifiers\UserVerifier@verify',
             ],

        'refresh_token' => [
            'class' => 'League\OAuth2\Server\Grant\RefreshTokenGrant',
            'access_token_ttl' => 604800,
            'refresh_token_ttl' => 604800
        ],
    ],

And change ‘access_token_ttl’ value to ‘access_token_ttl’ => 604800, //As it is in the grant_type array.

 Step 9 : Create client_id and client_secret to your database.

You can see oauth_clients table in your database there you want to add your client instances.

create model :

php artisan make:model OAuthClient

It will create the model inside your App folder

 

 <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class OAuthClient extends Model
{
    protected $table = 'oauth_clients';

    protected $fillable = ['id', 'secret', 'name'] ;
}

 Step 10 : Create seeder to insert instances

php artisan make:seeder OAuthClientTableSeeder

It will create a OAuthClientTableSeeder.php file under seeder folder and modify like below.

<?php

use Illuminate\Database\Seeder;

class OAuthClientTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //Create Own Instance of AOAuth Client.
        \App\OAuthClient::create(
        	[
        	'id' => 'webapp',
        	'secret' => 'pyRmmKK3cbjouoDMLXNtt2eGkyTTAG',
        	'name' => 'Laravel'
        	]);

        //Create Own Instance of AOAuth Client.
        \App\OAuthClient::create(
        	[
        	'id' => 'client1',
        	'secret' => 'client1secret',
        	'name' => 'android'
        	]);
    }
}

 

Step 11 : Feed seeder.

php artisan db:seed --class=OAuthClientTableSeeder

 Step 12 : Create UserVerifier.php

we have callback in our oauth2.php grant_type array
‘callback’ => ‘App\Verifiers\UserVerifier@verify’,

Create a folder called Verifiers inside App folder.
Create UserVerifier.php file like below

<?php

namespace App\Verifiers;
use Auth;

class UserVerifier
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function verify($username, $password)
    {
        $credentials = [
        'email' => $username,
        'password' => $password
        ];
        if(Auth::once($credentials))
        {
            return Auth::user()->id;
        }
        return false;
    }
}

Step 13 : Create a route to issue Authorize token

$api->version('v1', function($api) 
{
	$api->post('oauth/access_token', function() 
		{
			return Authorizer::issueAccessToken();
		});
});

Goto Postman to check how api works

1. Select your method : POST
2. Enter your url : http://domain.com/api/oauth/access_token
3. Select Body 
Provide below key and value
username => your username
password => your password 
grant_type => password
client_id => webapp 
client_secret => pyRmmKK3cbjouoDMLXNtt2eGkyTTAG

By clicking send button you will receive new token,

{
“access_token”: “eBmSfnxuiJ3iYH7kTs2wKBu4rAExcp2dEPJTMNXT”,
“token_type”: “Bearer”,
“expires_in”: 604800,
“refresh_token”: “ld9cVZUBdtssUQaaLWbFggwEDrdYFSiaGfiViFYf”
}

You can use this token for your further request.

 

Step 14 : Create Token Based authentication

Create Route like below to check token based authentication.

$api->version('v1', ['middleware' => 'api.auth'], function($api)
{
	$api->get('users', 'App\HTTP\Controllers\HomeController@users');
});

Inside my HomeController I have function called users. It wil looks like below :

 public function users()
    {
        return User::all();
    }

 Step 15 : Goto Postman to check how api works

1. Select method : GET
2. Enter URL : http://homestead.app/api/users
3. Select Body

Provide below key and value

Your Authorization header should be Bearer <token> // which is get by using http://domain.com/api/oauth/access_token

Authorization => Bearer XVCaKZXPbn1Sonh2hjFuqPBmVrehuURyAqC15aDY

By clicking send button you will receive all the users,

{
“users”: [
{
“id”: 1,
“name”: “Marimuthu”,
“email”: “event1@event.com”,
“created_at”: “2016-06-28 07:48:46”,
“updated_at”: “2016-06-28 09:36:08”
},
{
“id”: 2,
“name”: “Marimuthu”,
“email”: “marimuthut@gmail.com”,
“created_at”: “2016-06-28 07:49:41”,
“updated_at”: “2016-06-28 07:53:40”
}
]
}

 

 

Thats it now you have successfully installed Token Based authentication.
Thanks for reading.
If you like this article don’t forget to share and comment.
Thanks!.

 

Marimuthu:

View Comments

  • So how to distribute the client_id, client_secret and grant_type to our client while they request a login & registration ?

    • client_id, client_secret and grant_type are static which are srored in table, So you can give details to them directly

      For Other way,
      Ask your client to Create ONE API TO COLLECT "client_id, client_secret and grant_type".

      Ex : 17educations.com/api/fetch/client/credentials
      this URL will return client_id, client_secret and grant_type to client. // we need to return the details to cleint if they request above URL.

      By using that API URL, Client can collect "client_id, client_secret and grant_type". Even if you change the client_id, client_secret based on IP it does not matter it will get the detaisl from table and return to client.

      Thanks!.

    • Hello,

      Please look at the image : http://www.17educations.com/wp-content/uploads/2016/06/postman-gettoken.png
      By this way you need to pass your client_id, client_secret and grant_type to your appplications.

      For Grant Type : "Step 8 : Add grant_type with in the array with in the oauth2.php" // Refer the step 8;

      For Example :

      Your api URL : 17educations.com/api/login
      Your method : POST
      Your Form fields :
      [
      'username' => 'username',
      'password' => 'password',
      'grant_type' => 'password' // Refer step 8
      'grant_id' => '*********', // Refer step 10

      'grant_secret' => '*********' // Refer step 10

      ];

      Thanks!,.