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

terry's avatar
Level 1

Sending an Ajax Request to a route with 'web' and 'auth:web' middleware without changing the original CSRF Token

I am using JWT to authenticate API in Laravel 5.3. I am trying to use the same JWT authentication for AJAX Requests from Web and from mobile. The token in web will be generated using the authenticated user stored in session created by Laravel's default authentication service.

JWT Package:

"require": {
    "typmon/jwt-auth": "^0.5.9"
}

Controller Method to generate token.

public function getAuthToken(Request $request) {
    $token = JWTAuth::fromUser(\Auth::user());

    return Response::json(['_token' => $token]);
}

However to use \Auth::user(), this method must be in 'web' and 'auth:web' middleware.

$this->middleware('web',['only' => 'getAuthToken']);
$this->middleware('auth:web',['only' => 'getAuthToken']);

But after hitting this method as an ajax call from a page, the original CSRF token in that page is no longer valid.

Is there any way to work around this problem?

0 likes
0 replies

Please or to participate in this conversation.