Laravel Passport, Create REST API With Authentication

Abdelkader MOUDJAR
4 min readMay 11, 2019

--

Application Program Interfaces, APIs, are snippets of code that allow one software application to talk to another, providing a common language. Whether allowing seamless experiences for end users across multiple applications, or allowing data from one application to be fed into another, APIs have revolutionised in the last years.

If you are a beginner and you are learning and figuring out how to make apis and secure them, then you came to the right place, in this article i will show you how to set up an api authentication.

What is passport ?

Laravel Passport is a full OAuth2 server implementation, it was built to make it easy to apply authentication over an API for laravel based web applications.

Lets start

After setting up laravel and installing composer please follow the following steps:

1- Install Passport via the Composer package manager:

composer require laravel/passport

the passport package will register its own database migrations.

2- Migrate the passport tables:

php artisan migrate

3- Install passport:

php artisan passport:install

This command will create the encryption keys needed to generate secure access tokens.

4- Configuring passport:

add the Laravel\Passport\HasApiTokens trait to your App\Usermodel.

→ /project/app/User.php

Call Passport::routes method within the boot method of your AuthServiceProvider

→ /project/app/Providers/AuthServiceProvider.php

Set the driver option of the api authentication guard to passport

→ /project/config/auth.php

5- Creating the routes

→/project/routes/api.php

<?phpuse Illuminate\Http\Request;/*| — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —| 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::post(‘login’, ‘AuthController@login’);Route::post(‘register’, ‘AuthController@register’);Route::middleware(‘auth:api’)->get(‘/user’, function (Request $request) {return $request->user();});

6- Creating the controller

php artisan make:controller AuthController

then just copy and paste the code below to your AuthController :

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\Http\Controllers\Controller;use App\User;use Illuminate\Support\Facades\Auth;use Validator;class AuthController extends Controller{/*** login api** @return \Illuminate\Http\Response*/public function login(){if(Auth::attempt([‘email’ => request(‘email’), ‘password’ => request(‘password’)])){$user = Auth::user();$success[‘token’] = $user->createToken(‘myApp’)-> accessToken;return response()->json([‘success’ => $success], 200);}else{return response()->json([‘error’=>’Unauthorised’], 401);}}/*** Register api** @return \Illuminate\Http\Response*/public function register(Request $request){$validator = Validator::make($request->all(), [‘name’ => ‘required’,‘email’ => ‘required|email’,‘password’ => ‘required’,‘confirm_password’ => ‘required|same:password’,]);if ($validator->fails()) {return response()->json([‘error’=>$validator->errors()], 401);}$input = $request->all();$input[‘password’] = bcrypt($input[‘password’]);$user = User::create($input);$success[‘token’] = $user->createToken(‘myApp’)-> accessToken;$success[‘name’] = $user->name;return response()->json([‘success’=>$success], 200);}}

Before your application can issue personal access tokens, you will need to create a personal access client:

You need to create a personal access token

php artisan passport:client --personal

Finally, let’s try our register and login functionality :

php artisan serve

For me, i’m using insomnia for HTTP-based APIs, to send http requests.

By sending a register request with all the data needed we can see a success response from our api , with a special token, we can use this token to communicate with the api.

Now, after that if we disconnect or the token has expired we can login again and get our token, throw the login api :

--

--