Laravel 9 Custom Token Based Api Authentication Tutorial

Hello Artisan,

In this Laravel api authentication tutorial, I am going to show you laravel custom api authentication example. We can create api authentication using Laravel passport or JWT very easily. But in this example, I will show you the way to create api authentication example using custom token and without passport and jwt.

So hope, from this tutorial, you will learn how to create laravel api authentication token tutorial. So if you don't know how to create a token based api authentication, then this example is for you. I will use Laravel 9 fresh application to create this Laravel 9 token api authentication example.

So in this laravel token authentication, I will show you the login, register and logout system using custom authentication. So let's see how we can create Laravel 9 custom token based api authentication example.

 

Step 1 : Install Laravel

In the first step, we require to get a fresh Laravel application using bellow command, So open your terminal and run below command to get a fresh laravel application:

composer create-project --prefer-dist laravel/laravel ApiAuth

 

Step 2: Update Auth.php

As we are going to create a custom token based API authentication example without passport or jwt, we need to configure auth.php file like below:

config/auth.php

'guards' => [
    'web' => [
            'driver' => 'session',
            'provider' => 'users',
   ],
     'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
   ],
],

 

Step 3: Create Migration

In this step, we need to update users table and User model to create api token authentication. So update it like below:

app/Models/User.php

namespace App\Models;

use App\Helper\Tokenable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

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

    protected $fillable = [
        'name',
        'email',
        'password',
        'image'
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function saveUser($request) : self
    {   
        $this->name = $request->name;
        $this->email = $request->email;
        $this->password = bcrypt($request->password);
        $this->save();
        
        return $this;
    }

}

 

And now update the database like:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('api_token')->nullable();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
};

 

And now run php artisan migrate command to update the migrations.

 

Step 4: Create Tokenable Trait

Now we have to create a custom tokenable trait to generate custom api_token for user api authentication. So create it like below:

app\Helper\Tokenable.php

namespace App\Helper;

use Illuminate\Support\Str;

Trait Tokenable 
{
    public function generateAndSaveApiAuthToken()
    {
        $token = Str::random(60);

        $this->api_token = $token;
        $this->save();

        return $this;
    }
}

 

Step 5: Create Routes

Now in this step, we have to create api routes for custom token based api authentication examples. So create it like:

routes/api.php

use App\Http\Controllers\AuthController;
use Illuminate\Support\Facades\Route;

Route::post('register',[AuthController::class,'register']);
Route::post('login',[AuthController::class,'login']);

Route::group(['middleware' => ['auth:api']], function () {
    Route::post('logout', [AuthController::class, 'logout']);
});

 

Step 6: Create Controller

Now in this final step, we have to create our AuthController to complete that method like login, register and logout. 

app\Http\Controllers\AuthController.php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    public function register(Request $request, User $user)
    {
        return $user->saveUser($request)
            ->generateAndSaveApiAuthToken();
    }

    public function login(Request $request)
    {
        $credentials = [
            'email' => $request->email,
            'password' => $request->password,
        ];

        if (Auth::guard('web')->attempt($credentials)) {
            $user = Auth::guard('web')
                        ->user()
                        ->generateAndSaveApiAuthToken();

            return $user;
        }

        return response()->json(['message' => 'Error.....'], 401);
    }

    public function logout(Request $request)
    {
        $user = Auth::guard('api')->user();

        if ($user) {
            $user->api_token = null;
            $user->save();
        }

        return response()->json(['Success' => 'Logged out'], 200);
    }
}

 

Read also: Building a REST API with Laravel Microservices Lumen

 

Everything is set to go. Now run php artisan serve command and test our api like below:

 

register
http://127.0.0.1:8000/api/register

 

login
http://127.0.0.1:8000/api/login

 

logout
http://127.0.0.1:8000/api/logout

 

Recommended: API Authentication Tutorial with Laravel Passport

 

Hope this Laravel token api authentication tutorial will help you.

 

#laravel #laravel-9x #api-authentication