最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

rest - Auth::user() Returns null Even with Valid Token (Laravel Sanctum) - Stack Overflow

programmeradmin5浏览0评论

I'm working on a Laravel 11 API using Sanctum for authentication. I have a route protected by the auth:sanctum middleware, and I'm sending a valid token in the request header. However, when I try to get the authenticated user with:

  // Obtener el perfil del usuario autenticado
    public function getAuthenticatedUser()
    {
         return Auth::user();
    }
 public function getProfile()
    {
        try {
            $user = $this->userService->getAuthenticatedUser();
            return response()->json(['user' => $user], 200);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Error inesperado: ' . $e->getMessage()], 500);
        }
    }

and it´s returns { "error": "Usuario no encontrado" }

on postman and on my frontend app with react.

What I've checked so far: The token exists in the personal_access_tokens table and is linked to a valid user. The middleware auth:sanctum is applied correctly to the route. I've tried running php artisan tinker and Auth::user() also returns null. Double-checked that I'm using use Illuminate\Support\Facades\Auth; (not the wrong Auth class). Possible Causes? What else should I check? Could there be an issue with my middleware configuration or token validation? Any advice would be appreciated.

Thanks in advance!

发布评论

评论列表(0)

  1. 暂无评论