Laravel Rest API

Laravel Rest API

Install Laravel Passport:

Run the following command from the terminal to install the Laravel Passport package using the composer.

composer require laravel/passport

Go to the Laravel project folder and run the following migrate command to create the users table.$ php artisan migrate

Run the following command to install the passport package for the project.$ php artisan passport:install

You will get the following information after installing Laravel passport successfully in your project. Here, two secret keys are generated. One for personal access client and another for password grant client.

Laravel Passport Configuration:

Open the User model which is located in the location, App\Models\User.php from an editor, and modify the model like below. Add Laravel\Passport\HasApiTokens at the beginning of the class and use HasApiTokens and Notifiable inside the class.

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

Next, open app/Providers/AuthServiceProvider.php to register the routes that are necessary to issue and revoke access tokens. Passport::routes method is called within the boot method of AuthServiceProvider. Modify the content of the file shown below.

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();
        Passport::tokensExpireIn(now()->addDays(15));
        Passport::refreshTokensExpireIn(now()->addDays(30));
    }
}

Open config\app.php and insert the following line in the providers array to include the necessary class for using Laravel passport.

Laravel\Passport\PassportServiceProvider::class,

Open config\auth.php and set the driver of API to passport 

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

'api' => [
    'driver' => 'passport',
        'provider' => 'users',
        'hash' => false,
    ],
],

Implement Controller for Registration and Authentication:

You have to create a controller for implementing the authentication system using the passport package.

php artisan make:controller AuthController

A. Auth:

Any user can be authenticated by implementing the auth() method. Add the following code inside AuthController to implement a login API. If the authentication fails then an Unauthorized message will be returned.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    public function auth(Request $request)
    {
        /**Read the credentials passed by the user
        */
        $credentials = [
            'email' => $request->email,
            'password' => $request->password
        ];

        /**Check the credentials are valid or not
        */
        if( Auth::guard('web')->attempt($credentials) ){
            $user = Auth::user();
            $success['token'] = $user->createToken('myapi')->accessToken;
            return response()->json(['success' => $success], 200);
        } else {
            return response()->json(['error'=>'Unauthorised'], 401);
        }
    }
}

API Route:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

// Route::middleware('auth:api')->get('/user', function (Request $request) {
//     return $request->user();
// });

/**Route for auth API */
Route::post('auth', 'AuthController@auth');

/**Route for details user API */
Route::middleware('auth:api')->group(function(){
    Route::get('user', 'UserController@index');
});

Run the following command to start the Laravel development server.

$ php artisan serve

Test API authentication using postman:

Postman is a very useful tool to test RESTful APIs. The HTTP request can be generated very easily to test API functionalities by using the user interface of this application without writing a large amount of code to send requests. Postman can handle various HTTP requests and utilities to develop APIs. It has both paid and free versions for Linux.

http://localhost:8000/api/auth

Test User Details API:

Some header parameters are required to set up before sending the request for Details API. Click on the headers tab of the request section and add three header values to identify the authenticated user. The token value is copied from the response body and set for the Authorization value.Accept: application/json
Content-Type: application/json
Authorization:

The headers section of the request part will be looked like the following image. You have to set your token value that is generated in the response body of your postman agent.

Next, click on the Authorization tab of the request section and select Bearer Token as authorization type from the Type drop-down.

http://localhost:8000/api/user

Conclusion:

Passport authentication is using in many Laravel websites now for its useful features. It makes the Laravel authentication system more secure than the default authentication and provides other services that are not available in default authentication.

Leave a Reply

Close Menu