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

rcvioleta's avatar

Allow web authenticated users to access api endpoints.

Hello everyone! I want to authenticate users using the web route and allow access to the api routes that are protected with sanctum middleware 'auth:sanctum'. To achieve this, whenever a user is authenticated, I return the view and attached sanctum token in the cookie.

public function login(Request $request) {
    if (!Auth::attempt($request->only('email', 'password'))) {
        return response()->json([
            'success' => false,
            'message' => 'Login failed'
       ], Response::HTTP_UNAUTHORIZED);
   }

  $token = auth()->user()->createToken('token')->plainTextToken;
  $expiration = 60 * 24; // 24hrs
  $cookie = cookie('token', $token, $expiration);

  return response()->json([
       'success' => true,
       'message' => 'Login successful'
  ], Response::HTTP_ACCEPTED)->withCookie($cookie);
}

The purpose of this is to omit the frontend to manually set the 'Authorization' in the header like so:

const response = await fetch('/api/user', {
    method: 'GET',
    credentials: 'include',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    }
});

The problem is although I have set the 'Authorization' header in the middleware, it still returns 401 when I try to access the api route. I tried to die dump the $token and it has the correct sanctum token. I am able to access the api routes when I use postman or insomnia but it doesn't work in the web when I try to send http request via javascript fetch api.

Here is my middleware:

<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
use Closure;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     */
    protected function redirectTo(Request $request): ?string
    {
        return $request->expectsJson() ? null : route('login');
    }

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

        if (!is_null($token)) $request->headers->set('Authorization', 'Bearer ' . $token);

        $this->authenticate($request, $guards);

        return $next($request);
    }
}
0 likes
4 replies
martinbean's avatar

To achieve this, whenever a user is authenticated, I return the view and attached sanctum token in the cookie.

@rcvioleta Why not use Sanctum the way it was intended to be used? Now any one inspecting network traffic has a plaintext token that they can use to make authenticated requests.

1 like
rcvioleta's avatar

Hey @martinbean! Thank you for taking time to reply. The frontend is in the root domain 'web' routes (which I don't have control over/unchangeable circumstance) and Laravel prevents editing cookies and I don't want to store the token in local storage or session storage.

1 like
martinbean's avatar
Level 80

@rcvioleta But if you use Sanctum as it’s intended to be used then you wouldn’t be storing the token in the first place.

You should only be using API tokens for things like mobile apps. Use cookies for your web app.

1 like

Please or to participate in this conversation.