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:
-
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
Authorizationheader as a Bearer token. -
Manually Authenticate the User:
Use the
Sanctumtoken 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:
use Illuminate\Http\Request;
use Laravel\Sanctum\PersonalAccessToken;
use Illuminate\Support\Facades\Auth;
public function yourPublicEndpoint(Request $request)
{
// Extract the token from the Authorization header
$token = $request->bearerToken();
if ($token) {
// Find the token in the database
$accessToken = PersonalAccessToken::findToken($token);
if ($accessToken) {
// Get the associated user
$user = $accessToken->tokenable;
// Manually set the authenticated user
Auth::setUser($user);
}
}
// Now you can use $request->user() or Auth::user() to get the authenticated user
$authenticatedUser = $request->user();
// Your logic here
return response()->json([
'authenticated_user' => $authenticatedUser,
]);
}
Explanation:
- Extracting the Token: The
bearerToken()method is used to extract the token from theAuthorizationheader. - 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()orAuth::user().
This approach allows you to keep the endpoint public while still being able to authenticate users who provide a valid token.