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

netdjw's avatar
Level 15

Resolve authenticated user from XSRF-Token cookie

I have a public route what can see users without login. This route leads to a component class. In this componentet's blade I want show more information if the user logged in.

The issue is I log in with Axios, receive XSRF-Token cookie in client, the cookie is stored and applied on each requests. So when I load the component's page, I can see the XSRF-Token in Request::cookies, but the Auth::user() is null.

How can I resolve Auth::user() in the Component class?

0 likes
14 replies
lbecket's avatar

You can resolve the authenticated user in the component class by using the Auth facade in the mount method of the component. The mount method is called once when the component is first rendered.

class MyComponent extends Component
{
    public $user;

    public function mount()
    {
        $this->user = Auth::user();
    }

    public function render()
    {
        return view('my-component', [
            'user' => $this->user
        ]);
    }
}

In this example, the authenticated user is resolved in the mount method and stored in the $user property. The $user property can then be accessed in the view for the component.

netdjw's avatar
Level 15

@lbecket I put a dd() into mount() but nothing happend. If I put dd into render(), it works.

thinkverse's avatar

You'll want to resolve the authenticated user in the component constructor if you're using a Blade component. Also, keep in mind that $user will be null if the component is loaded and no authenticated user is found.

use Illuminate\Support\Facades\Auth;
use Illuminate\View\Component;

class MyComponent extends Component
{
    public $user;

    public function __construct()
    {
        $this->user = Auth::user();
    }

    public function render()
    {
        return view('components.my-component');
    }
}

That will make the authenticated user available as a $user variable.

{{-- components/my-components.blade.php --}}
<div>
    {{ dd($user) }}
</div>
netdjw's avatar
Level 15

@thinkverse Thanks for your detailed answer.

My problem is: even if I try to resolve authentinticated user in the controller (what calls the component class) the Auth::user() always return null. But I see Laravel receives the XSRF-Token cookie.

So I don't understand why isn't parsed the cookie and found the user.

thinkverse's avatar

@netdjw because the XSRF-token isn't used for that purpose? It's used for CSRF Protection to prevent cross-site request forgery attacks.

Laravel stores the current CSRF token in an encrypted XSRF-TOKEN cookie that is included with each response generated by the framework. You can use the cookie value to set the X-XSRF-TOKEN request header.

The Auth facade will find the user based on the guard, that's usually the web guard which uses sessions, or whatever your default auth guard is - configured in config/auth.php under defaults.guard, how those are stored is configured in your config/sessions.php file, by default they're stored in encrypted files under storage/framework/sessions.

If the facade cannot resolve the user, it means you're either not logged in, or you're using another guard than the default, you can access a specific guard instance using the guard method if you're using a custom guard, or set your custom guard to the default.

Auth::guard('my-guard')->user();
netdjw's avatar
Level 15

@thinkverse So, okay, I read the documentation again meanwhile. Now I know not the XSRF-TOKEN matter, but laravel_session cookie does. But I have this cookie too and it contains a valid token.

What you suggest I tried:

        dd(
            Auth::guard('sanctum')->user(),
            Auth::guard('web')->user(),
            Auth::guard('api')->user(),
        );

All three returns null.

thinkverse's avatar

@netdjw well not really, the laravel_session doesn't store the authentication session, at least not in Laravel 9, it stores the key to it though. For instance, if I decrypt the laravel_session it'll contain a pipe-separated string, and one of those values will be the key to the authentication session.

Where that session is stored is up to you by setting the SESSION_DRIVER environment variable, it is set to file by default, like the default fallback in config/session.php if the variable isn't set.

If you tried all guards and it still returns null, then the user simply isn't logged-in at all.

netdjw's avatar
Level 15

@thinkverse @snapey Then the next question is when I call the auth route from Vue with this code:

    login(creadentials) {
        Axios.get('/sanctum/csrf-cookie').then(response => {
            // I get status: 204, statusText: 'No Content' in response
        });

        Axios.post('/auth/login', creadentials)
            .then(response => {
                if(response.status === 200) {
                    localStorage.setItem('memberToken', response.data.token);
                    localStorage.setItem('member', JSON.stringify(response.data.member));
                }
            })
            .catch(error => {
                // ...
            });
    },

...and I receive this from /aut/login route:

{
    "token": "134|GfKRlo1M9XFQEXyQ9zDGfgVVnAqOJheTqLHkWBl9",
    "token_expire_at": null,
    "token_type": "bearer",
    "member": {
        "id": 8,
        "name": "omnis qui asperiores",
        "email": "[email protected]",
        "user": "qui",
        "last_login_at": "2012-10-15T08:22:36.000000Z",
        "phone": "605-772-5570",
        "customer_id": 9,
        "foreign_id": "officiis"
    }
}

It seems to me it's good and the login happend.

Maybe I should get anything else too? Or... (I feel I miss something.)

thinkverse's avatar

@netdjw that doesn't seem like a starter kit from Laravel, those all use stateful authentication, even the SPAs do, but this returns a bearer token. A token, which needs to be sent in the header for each request sent by Vue and Axios so that Santcum can verify it.

When the mobile application uses the token to make an API request to your application, it should pass the token in the Authorization header as a Bearer token.

// Axios config object.
const config = {
  headers: {
    Authorization: "Bearer 134|GfKRlo1M9XFQEXyQ9zDGfgVVnAqOJheTqLHkWBl",
  }
};

Your browser won't send the bearer token with each request like a session or cookie, so if your app is browser-based stick with stateful or session-based authentication. Otherwise, you'll need to have everything behind an API that needs to be called with the bearer token in the header on each request. Since your browser doesn't send the token, the first request will always be unauthenticated.

netdjw's avatar
Level 15

@thinkverse I understand. But as I said earlier: I use Axios to get a token, and I want to authenticate the user in a regular GET request (not SPA). I belived the XSRF-TOKEN do the authentication, but not. And now I have no idea how can I say to laravel on a regular GET request the user is authenticated if nor XSRF-TOKEN, nor laravel_session cookie doesn't matter.

Do you have any idea?

thinkverse's avatar

@netdjw you can't, if you're using token-based authentication, meaning your client side receives a token from your backend then each full page reload will be unauthenticated because the server won't have any way of knowing if the user is authenticated since it hasn't set a session or created a cookie for you.

You will need to start the request unauthenticated, return your Vue app, and then inside your Vue app send an API call to the server using the provided token and check if the user is authenticated or not, then you can update your Vue app accordingly, that's how token-based authentication works.

netdjw's avatar
Level 15

I found a solution and my mistake: the token wasn't stored on the Member model. After I add this column in the database, and field to the model, and I store the received token on client as a cookie:

document.cookie = "token=" + response.data.token + ";path=/;expires=" + getExpirationDate();

function getExpirationDate() {
    let expirationDate = new Date();

    expirationDate.setTime(expirationDate.getTime() + (7 * 24 * 60 * 60 * 1000));

    return expirationDate.toUTCString();
}

Then the browser send this cookie with each requests and user can be identified.

For the identify user I created a middleware and add it to the app/Http/Kernel.php file's $middleware array. This is the code in the middleware:

<?php

namespace Domain\Auth\Http\Middleware;

use Closure;
use Domain\Customer\Models\Member;
use Illuminate\Support\Facades\Auth;

class CheckTokenCookieForMember
{
    public function handle($request, Closure $next)
    {
        $token = $request->cookie('token');

        if (!$token) {
            return $next($request);
        }

        $member = Member::whereToken($token)->first();

        if ($member) {
            Auth::guard('web')->login($member);
        }

        return $next($request);
    }
}

Please or to participate in this conversation.