DEV Community

Moudjar Abdelkader
Moudjar Abdelkader

Posted on

Laravel Passport, Create REST API With Authentication

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

https://thepracticaldev.s3.amazonaws.com/i/ovyjolcls53zenwm2m7m.png

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

→ /project/app/Providers/AuthServiceProvider.php

https://thepracticaldev.s3.amazonaws.com/i/3yqsq0ut0lm6ik36t124.png

Set the driver option of the api authentication guard to passport

→ /project/config/auth.php

https://thepracticaldev.s3.amazonaws.com/i/xjecpwgz8x14bz9ms7ox.png

5- Creating the routes

→/project/routes/api.php

<?php
use 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 :

<?php
namespace 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.

https://thepracticaldev.s3.amazonaws.com/i/69j0jgndf38s5jkfktc5.png

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 :

https://thepracticaldev.s3.amazonaws.com/i/qibwbe4h3s3xcopsqwdt.png

Top comments (5)

Collapse
 
kevinkuyl profile image
Kevin Kuyl

please use proper formatting or screen shots to mark up your code. this is hard to read.

Collapse
 
miguel456 profile image
Miguel Nogueira

this is awfully hard to read, and leaving dev to open screenshots is another bad user experience ╯°□°)╯︵ ┻━┻

Collapse
 
programmermarvin profile image
Marvin

This kind of articles should be flagged down

Collapse
 
alabs02 profile image
Snapster02

Nice post, but use the polacode extension in vscode to take good snippets of the code cause this is difficult to read

Collapse
 
impactcolor profile image
Omar Guzman

"Just copy and paste controller code". It'll give an error the way it's formatted you can't tell where it starts or ends.