Laravel REST API — 1. Authentication

Zeba Rahman
fabcoding
Published in
3 min readAug 7, 2020

Laravel makes API authentication a breeze using Laravel Passport, which provides a full OAuth2 server implementation for your Laravel application in a matter of minutes.

If you are new to Laravel, I suggest you go through this article first to learn how to set up and create a new project.

Once you have a project, you can continue below.

Step 1

Install Passport

In your laravel project, run the command

composer require laravel/passport

and then run migrate command to create all the necessary tables.

php artisan migrate

Finally, install it

php artisan passport:install

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

Step 2

Configure Project

We will make changes in the following 3 files:

1. app/User.php

Add the following line at the top

use Laravel\Passport\HasApiTokens;

And inside the class add this usage of HasApiTokens;

The user class should now look like this

<?php

namespace App;

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

class User extends Authenticatable {
use HasApiTokens, Notifiable;
...//more code
}

2. app/Providers/AuthServiceProvider.php

Here we need to add Passport routes in the boot() function. Make the following changes which are in bold.

<?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 {
... //more code

public function boot() {
$this->registerPolicies();
Passport::routes();
}
}

This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens.

3. config/auth.php

Here, set the driver option of the api authentication guard to passport.

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

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

Step 3

The controller

Now we will make the controller for handling the logic of the authentication routes. Run the following command to create a controller, We shall create this inside a new namespace for the Api, so that all your API controllers can be separate for cleaner architecture.

php artisan make:controller Api/AuthController

Go to the newly created file in app/Http/Controllers/Api/AuthController.php

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\User;

class AuthController extends Controller
{

}

Add the methods for login, register, logout and one for getting the user detail

public function register(Request $request) {
$validatedData = $request->validate([
'name' => 'required|max:55',
'role' => 'required|max:55',
'email' => 'email|required|unique:users',
'password' => 'required|confirmed'
]);

$validatedData['password'] = bcrypt($request->password);
$user = User::create($validatedData);
$accessToken = $user->createToken('authToken')->accessToken;

return response([ 'user' => $user, 'access_token' => $accessToken]);
}

public function login(Request $request) {
$loginData = $request->validate([
'email' => 'email|required',
'password' => 'required'
]);

if (!auth()->attempt($loginData)) {
return response(['message' => 'Invalid Credentials']);
}

$accessToken = auth()->user()->createToken('authToken')->accessToken;
return response(['user' => auth()->user(), 'access_token' => $accessToken]);
}

public function logout(Request $request) {
$request->user()->token()->revoke();
return response()->json([
'message' => 'Successfully logged out'
]);
}

public function user(Request $request) {.
return response()->json($request->user());
}

Step 4

The routes

Now the last step is to configure the routes for accessing the api functions.

Go to routes/api.php file and add the following routes, for each of the functions we wrote in our controller.

Route::post('/register', 'Api\AuthController@register');
Route::post('/login', 'Api\AuthController@login');
Route::post('/logout', 'Api\AuthController@logout');

Now you are ready to test your api!

Test

Open Postman and test the endpoints.

POST http://localhost:8000/api/login

Similarly, you can pass the parameters for the register endpoint and test it.

Originally published at Fabcoding.

--

--