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

Gabotronix's avatar

Laravel - React Native : Sanctum getting 302 redirects to homepage

I have a laravel backend and a react native frontend, I want to protect the api routes that are hit from my react native app with axios, for this I installed laravel sanctum.

My current workflow is : I log or register user with email and password, get a sanctum token that I store using AsyncStorage in my app, then I send this token on the headers of all my axios calls uisng interceptors.

THE ISSUE:

Routes protected by auth:sanctum middleware get a 302 Found, then redirected to homepage / 200 OK.

How I create a token in backend:

$token = $user->createToken($request['device_name'])->plainTextToken;

How I add my Bearer toke to headers (I verify they are attached via console log):

if (token) 
{
    console.log('SANCTUM: Adding bearer token to axios: ' + token);
    axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
}

How I protect my routes:

Route::get('/auth/sanctum/user', 'App\Http\Controllers\Api\AuthController@sanctumUser')->middleware('auth:sanctum');

In my RedirectIfAuthenticated middleware I tried changing it after reading some other posts but any i change I made it did not made any difference...

In my Kernel http:

protected $middlewareGroups = [
        'web' => [
            //\App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            //\Illuminate\Session\Middleware\StartSession::class,
            //\Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
        
        
        'api' => [
            //EnsureFrontendRequestsAreStateful::class,
            \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
        
    ];

sanctum.php file

auth.php file:

0 likes
0 replies

Please or to participate in this conversation.