Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

aknEvrnky's avatar

Getting Authenticated user on API routes

Hey, I've a public api endpoint which is not secured by auth:sanctum middleware in routes/api.php file. I need to have access to user if they send their token via header.

If I use the auth:sanctum middleware, I can get the authenticated user via either $request->user() or Auth::user() but I don't want to use the middleware since this endpoint is public.

But If I do not use any middleware, I cannot get the user even they send their token. Actually, this is the expected behavior because there is no logic in api middleware group that checks for sanctum guard and passes it to request (or auth facade).

So, how can I achieve this behavior? My code has a logic that checks for whether user is authenticated or not. Maybe Auth::guard('sanctum') can be used but I also use Policy class with Guest Users feature. I don't think Auth::guard('sanctum') is a permanent solution.

0 likes
5 replies
LaryAI's avatar
Level 58

To achieve the behavior where you can access the authenticated user without applying the auth:sanctum middleware to your public API endpoint, you can manually authenticate the user using the token from the request headers. Here's how you can do it:

  1. Extract the Token from the Request Headers:

    First, you'll need to extract the token from the request headers. Typically, the token is sent in the Authorization header as a Bearer token.

  2. Manually Authenticate the User:

    Use the Sanctum token model to find the user associated with the token. You can then manually set the authenticated user in the request.

Here's a code example demonstrating how you can achieve this:

Explanation:

  • Extracting the Token: The bearerToken() method is used to extract the token from the Authorization header.
  • Finding the Token: The PersonalAccessToken::findToken($token) method is used to find the token in the database.
  • Setting the User: If a valid token is found, the associated user is retrieved and set as the authenticated user using Auth::setUser($user).
  • Accessing the User: You can now access the authenticated user using $request->user() or Auth::user().

This approach allows you to keep the endpoint public while still being able to authenticate users who provide a valid token.

1 like
jaseofspades88's avatar

Why would you want to have an endpoint that CAN accept a token but doesn’t need to? What use case are you dealing with?

aknEvrnky's avatar

@jaseofspades88 I've a Profile resource which returns User model's data. If the token is provided, I also add is_follower and is_following columns.

Also, my policy logic needs to access authenticated user. If user is guest, allow in some condition. If not a guest, check the user owner of the model or not.

aknEvrnky's avatar

After I inspected Auth codebase, I found a method Auth::shouldUse() which directly does what I wanted to do. With the combination of custom middleware,

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class UseSanctumGuard
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        Auth::shouldUse('sanctum');

        return $next($request);
    }
}

solved my issue. I hope this will be useful for whoever needs it

Please or to participate in this conversation.