Home > Software design >  How to detect Unavailability or Unauthenticated of Laravel Auth Sanctum Token for Mobile API
How to detect Unavailability or Unauthenticated of Laravel Auth Sanctum Token for Mobile API

Time:11-04

BACKGROUND

So I created a security process on routes/api.php in Laravel using auth:sanctum for mobile APIs like this:

Route::middleware('auth:sanctum')->group(function () {
    Route::get('profile', [UserController::class, 'profile']);
    Route::post('profile_update', [UserController::class, 'updateProfile']);
    Route::post('logout', [UserController::class, 'logout']);
});

I know to be able to access the APIs in it, then I need a PersonalAccessToken which can be generated like this:

$user = M_CRM_CUSTOMER::where('indexs', $user_indexs)->first();
$tokenResult = $user->createToken($request->mobile)->plainTextToken;

Which is where the code will populate the records in the personal_access_tokens table which is served automatically in the initial Laravel migration

Schema::create('personal_access_tokens', function (Blueprint $table) {
    $table->id();
    $table->morphs('tokenable');
    $table->string('name');
    $table->string('token', 64)->unique();
    $table->text('abilities')->nullable();
    $table->timestamp('last_used_at')->nullable();
    $table->timestamp('expires_at')->nullable();
    $table->timestamps();
});

CASE

Technically, as long as the Token is in the Database or as long as it hasn't expired, then we can access/use it against the APIs in the group, right? enter image description here

If you try to access the APIs in the group using Postman, it will work.

Now, if the User revokes the Token, using:
$token = $request->user()->tokens()->delete();

Then if we try to access the APIs contained in the group using Postman, it will result in a failed display in the form of HTML code from the Laravel login page. enter image description here

Maybe for web users this is helpful and viewable, but for Mobile API users?
There will definitely be an error.

EXPECTATIONS

My point is how do I know if the User is authenticated OR has a PersonalAccessToken using Sanctum? So that I can create a simple return message, in case the User is not authenticated.

Try 1

Maybe because I'm using auth:sanctum, I can't use enter image description here

  • Related