You already know that there are many convenient ways to create an API authentication system in the Laravel application. In this Laravel 10 API authentication tutorial, I will show you a complete tutorial of laravel api authentication token tutorial.

No sanctum, no passport, and no JWT (JSON Web Token) for API authentication. This time, I will use a custom token and then I will create a auth system with that token. I will generate sixty digit token for a user and using that token, we will create an authentication system in Laravel 10 application.

To create this laravel custom api authentication, we need an api_token column in our user's table. So let's see how to create laravel 10 api authentication with token.

 

Step 1: Install Laravel 10

First of all, we need to get a fresh Laravel 10 version application using the bellow command to start token based authentication examples in laravel.

composer create-project laravel/laravel example-app

 

Step 2: Connect Database

I am going to use the MYSQL database for this laravel api authentication without passport. So connect the database by updating.env like this:

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=YOUR_DB_NAME
DB_USERNAME=YOUR_DB_USERNAME
DB_PASSWORD=YOUR_DB_PASSWORD

 

And now update the database like:

<?php

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

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

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

 

Now run php artisan migrate command to migrate the database.

 

Read also: Laravel 10 JWT - Complete API Authentication Tutorial

 

Step 3: Confuring API Guard

Now in this step, we have to update and set up the API authentication guard. So update the following file like that:

config/auth.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session"
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expiry time is the number of minutes that each reset token will be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    | The throttle setting is the number of seconds a user must wait before
    | generating more password reset tokens. This prevents the user from
    | quickly generating a very large amount of password reset tokens.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_reset_tokens',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => 10800,

];

 

Step 4: Create Route

Here, we need to add routes to create this laravel api token authentication tutorial. So update the api routes file like this:

routes/api.php

<?php

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

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 5: Create Controller

Now we have to create AuthController to complete our laravel api authentication token tutorial. So run the below command to create a controller:

php artisan make:controller API/AuthController

 

Now update this controller like this:

app/Http/Controllers/API/AuthController.php

<?php

namespace App\Http\Controllers\API;

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

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $user = new User();
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = bcrypt($request->password);
        $user->save();

        return $user;
    }

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

        if (Auth::guard('web')->attempt($credentials)) {
            $user = Auth::guard('web')->user();
            $user->api_token = Str::random(60);
            $user->save();

            return $user;
        }

        return response()->json(['message' => 'Something went wrong'], 401);
    }

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

        return response()->json(['message' => 'You are successfully logged out'], 200);
    }
}

 

Now if you start your server by running php artisan serve and test all API via Postman like this:

REGISTER API
http://127.0.0.1:8000/api/register

 

And now see the Postman output:

laravel-10-custom-token-based-api-register

LOGIN API
http://127.0.0.1:8000/api/login

 

And look at that Postman output:

laravel-10-custom-token-based-api-login

LOGOUT API
http://127.0.0.1:8000/api/logout

 

Now see the Postman output. Don't forget to add a bearer token with your headers.

laravel-10-custom-token-based-api-authentication-tutorial

Read also: Laravel 10 Guzzle HTTP Client POST Request Example

 

Conclusion

After completing this laravel custom api authentication tutorial, hope now you can create this laravel api token authentication in your laravel 10 application. Hope this laravel 10 api authentication with token tutorial will help you.

Category : #laravel

Tags : #laravel , #laravel api