Skip to main content

Who Does auth()->id() Actually Return? Lessons Learned from Sanctum Polymorphic Tokens and a Dual Membership System

E

Editor

Flutter

October 31, 2026 15 reads
On this page

Preface

Look at this seemingly harmless piece of code:

$userId = auth('sanctum')->id();
if ($userId) {
    $res['isLiked'] = $this->likes()
        ->where('user_id', $userId)
        ->exists();
}

The semantics are clear: get the currently logged-in user, and check whether they have liked this comment.

But if your system has both "front-end members" and "back-end administrators" as two separate authenticated principals, this line is a time bomb. Because——

auth()->id() does not return the "member ID" but the ID of the "token owner." The token may belong to an administrator or a member; it could be either.

This article documents a real troubleshooting process: how the problem arose, why Sanctum is designed this way, and how to move from treating the symptom to fixing the root cause.

1. Sanctum tokens don't belong to a guard — they belong to a model

First, look at the core fields of the personal_access_tokens table:

create table personal_access_tokens (
    id              bigint unsigned not null auto_increment primary key,
    tokenable_type  varchar(255) not null,
    tokenable_id    bigint unsigned not null,
    name            varchar(255) not null,
    token           varchar(64)  not null,
    abilities       text null,
    ...
);

tokenable_type + tokenable_id form a polymorphic relation. In other words, Sanctum assumes from the very beginning that "a token can belong to any model."

During authentication, the Guard does something very straightforward:

$tokenable = $accessToken->tokenable->withAccessToken($accessToken);
return $tokenable;

It doesn't care what the guard is called, nor does it consult the provider; it simply returns the "owner" registered in the token record as-is.

As a result, the same auth('sanctum') will:

  • return an AdminUser instance for a token issued by an administrator
  • return a User instance for a token issued by a member

So the result of auth()->id() can naturally be one of two values. This is not an exceptional branch — it is the norm.

2. Why the default configuration doesn't prevent this

At this point you might ask: doesn't Laravel's guard have a provider? Why doesn't it stop this?

Because when Sanctum registers the guard, it deliberately sets the provider to null:

config([
    'auth.guards.sanctum' => array_merge([
        'driver' => 'sanctum',
        'provider' => null,
    ], config('auth.guards.sanctum', [])),
]);

And the provider validation implementation looks like this:

protected function hasValidProvider($tokenable)
{
    if (is_null($this->provider)) {
        return true;
    }
    $model = config("auth.providers.{$this->provider}.model");
    return $tokenable instanceof $model;
}

When provider is null, validation passes through directly.

In other words: "one guard authenticating multiple user types" is a deliberate design choice in Sanctum, not a bug. It assumes the token table already distinguishes principals via polymorphism, so there is no need to filter again via the provider.

This design works fine in an application with only one user system, but as soon as you have multiple systems, the risk is planted.

3. Where it bit us

The project context is simple:

  • Modules\Ucenter\Models\User — front-end members
  • Modules\Admin\Models\AdminUser — back-end administrators

Each issues its own tokens, distinguished by abilities:

// Front-end member
$this->createToken($this->username, ['front'])->plainTextToken;
// Back-end administrator
$this->createToken($this->username, ['admin'])->plainTextToken;

On the route level, abilities:front / abilities:admin block access, so at the API level things look isolated.

The problem lies in shared logic. The comment list's UserCommentResource is reused in three places:

  • front-end member comment list
  • back-end administrator comment management list
  • a newly added public comment API (accessible to guests)

The resource class contains this:

$userId = auth('sanctum')->id();
if ($userId) {
    $res['isLiked'] = $this->likes()
        ->where('user_id', $userId)
        ->exists();
}
$res['canEdit'] = $userId && $userId === $this->user_id;

And user_comment_likes.user_id and user_comments.user_id both store member IDs.

So when an administrator opens the back-end comment list, the following happens:

  1. auth('sanctum')->id() returns the administrator's ID;
  2. the code treats it as a member ID and queries user_comment_likes.user_id;
  3. whenever an administrator ID happens to collide with some member ID (the two tables auto-increment independently, so collisions are extremely common), the like status gets crossed;
  4. likewise, if the administrator ID happens to equal the comment author's ID, canEdit will be wrongly evaluated as true;
  5. every comment also incurs a wasted like-table query.

This is the most direct cost of "auth()->id() depends on who the token belongs to."

4. A more subtle pitfall: the default guard of Auth::check()

The original code wasn't auth('sanctum') — it was:

if (Auth::check()) {
    $res['isLiked'] = $this->likes()
        ->where('user_id', Auth::id())
        ->exists();
}

Auth::check() uses the default guard. In this project the default guard is front (session driver), while API requests carry a Bearer token, which the default guard cannot recognize at all.

So why did it "look fine" in some scenarios? Because after the auth:sanctum middleware authenticates successfully, it calls shouldUse('sanctum'), temporarily switching the default guard. As soon as a route doesn't have this middleware — for example, a public API accessible to guests — it immediately stops working, and even logged-in users can't get their like status.

Conclusion: don't rely on the implicit guard of Auth::xxx(); explicitly specify the guard you intend to use.

5. Treating the symptom: check the type before taking the ID

The lowest-cost fix is to do a type check before fetching the value:

// The token principal may be an administrator; distinguish front-end member / administrator
$authUser = auth('sanctum')->user();
$userId = $authUser instanceof User ? $authUser->id : null;
if ($userId) {
    $res['isLiked'] = $res['isLiked'] ?? $this->likes()
        ->where('user_id', $userId)
        ->exists();
} else {
    // Non-member tokens must not return like status, avoiding misjudgment from
    // administrator ID colliding with a member ID
    unset($res['isLiked']);
}
$res['canEdit'] = $userId !== null && $userId === $this->user_id;

Details worth noting:

  • User and AdminUser both directly extend Authenticatable with no inheritance relationship between them, so instanceof User distinguishes them accurately;
  • non-members always get null, so subsequent queries are naturally skipped;
  • the final unset is a safety net — even if upstream code mistakenly passes an administrator ID into the preloading, the wrong state won't leak to the front end;
  • don't use a helper that throws an exception when not logged in (like this project's frontUser()); public APIs cannot accept that.

This fix is correct enough, but it's defensive and relies on every call site remembering to do the check.

6. Treating the root cause: bind a provider to the guard

Sanctum itself provides an isolation mechanism — it's just not enabled by default: bind a provider to each guard.

// config/auth.php
'guards' => [
    'front' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
    // API token guard: once a provider is bound, Sanctum will validate the token principal's type
    'sanctum' => [
        'driver' => 'sanctum',
        'provider' => 'users',
    ],
    'sanctum_admin' => [
        'driver' => 'sanctum',
        'provider' => 'admins',
    ],
],

After configuration:

  • auth('sanctum') only accepts User; administrator tokens return null directly;
  • auth('sanctum_admin') only accepts AdminUser;
  • if the type doesn't match, authentication fails at the auth stage and returns 401.

Many people worry: "will defining another sanctum conflict with the one Sanctum auto-injects?" It won't. In that line array_merge(defaults, config('auth.guards.sanctum', [])), your configuration comes last, so it overrides the default provider => null. And two guards sharing driver => 'sanctum' is perfectly fine — just as the front / admin guards already share the session driver while each remains an independent guard instance.

Things that are easy to miss during the refactor:

  • replace all auth:sanctum on back-end routes with auth:sanctum_admin;
  • replace guest:sanctum on the login page with guest:sanctum_admin;
  • broadcast authentication Broadcast::routes(['middleware' => ['auth:sanctum', ...]]);
  • hard-coded auth('sanctum')->id() in back-end code;
  • Sanctum::actingAs($user, ['admin']) in tests — the third parameter is the guard name, defaulting to sanctum, so back-end test cases must explicitly pass sanctum_admin.

7. How to verify

Once the configuration is written, don't guess — look at the final result after the application boots:

php artisan config:show auth.guards

If the output shows sanctum.provider as users and sanctum_admin.provider as admins, the merge succeeded.

Then add a security-boundary test using real tokens (rather than actingAs, which bypasses provider validation):

  • a member token requests a back-end endpoint → 401
  • an administrator token requests a front-end endpoint → 401

8. Summary

  • Sanctum tokens are polymorphic; auth()->id() returns the ID of the "token owner," regardless of the guard's name — whoever issued the token is who it may return.
  • When a system has multiple authentication models, any shared user-related logic must first confirm the principal's type before using an ID.
  • Auth::check() / Auth::id() depend on the default guard and are unreliable in token-only scenarios; specify the guard explicitly.
  • Treat the symptom with instanceof type checks; treat the root cause by binding a provider to the guard for authentication-layer isolation.
  • abilities governs "what you can do"; provider governs "who you are." The two cannot substitute for each other.

A final word for my future self: the next time you see auth()->id(), first ask — whose token is this?


WeChat

Scan to add me on WeChat

WeChat QR code