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

Nourgeos's avatar

Unexpected 302 redirect after success login using Laravel Sanctum

I'm working on an application that relies on Laravel Sanctum for login. However, after deploying and running the application on the server, I encountered an issue where, after a successful login, it doesn't redirect to the dashboard page. Instead, it redirects to a page with a **status code 302 **and remains on the login page. Additionally, I receive an email notifying me that I have successfully logged in.

Note: The code works on the local server without any issues.

Certainly, I will attach the codes for the routes and login.

API Routes : Route::group(['prefix' => 'admin/auth'], function () { route::post('/login',[AuthController::class,'login'])->name('api_login'); Route::get('/logout', [AuthController::class, 'logout'])->name('api_logout'); });

Web Routes : Route::middleware('auth:sanctum')->prefix('admin')->group(function (){ Route::get('/overview', [OverviewController::class, 'index'])->name('overview'); Route::get('/orders', [OrdersController::class, 'index'])->name('orders'); });

AuthController -> Login Function : Part of PHP Collective 0

I'm working on an application that relies on Laravel Sanctum for login. However, after deploying and running the application on the server, I encountered an issue where, after a successful login, it doesn't redirect to the dashboard page. Instead, it redirects to a page with a **status code 302 **and remains on the login page. Additionally, I receive an email notifying me that I have successfully logged in.

Note: The code works on the local server without any issues.

Certainly, I will attach the codes for the routes and login.

API Routes :

Route::group(['prefix' => 'admin/auth'], function () { route::post('/login',[AuthController::class,'login'])->name('api_login'); Route::get('/logout', [AuthController::class, 'logout'])->name('api_logout'); });

Web Routes :

Route::middleware('auth:sanctum')->prefix('admin')->group(function (){ Route::get('/overview', [OverviewController::class, 'index'])->name('overview'); Route::get('/orders', [OrdersController::class, 'index'])->name('orders'); });

AuthController -> Login Function :

public function login(LoginRequest $request)
{
    try {
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            $user = Auth::user();
    
            if ($user->email_verified_at !== null) {
                // Generate a Sanctum token for the user
                $token = $user->createToken('auth-token')->plainTextToken;

                $ipAdress = $request->ipinfo->ip;
                //send login alert
                Mail::to($request->email)->send(new LoginAlert([
                    "CustomerName" => showUserName(),
                    "IpAdress"     => $ipAdress,
                    "Location"     => $request->ipinfo->country_name . ', ' . $request->ipinfo->city,
                    "BrowserOs"    => $request->header('User-Agent')
                ]));

                return ApiResponse::sendResponse(200, 'Authorized successfully', ['token' => $token]);
            }
            return ApiResponse::sendResponse(401, 'Email has not been verified', null);
        }
    
        return ApiResponse::sendResponse(401, 'Unauthorized', null);
    } catch (\Exception $th) {
        return ApiResponse::sendResponse(401, $th->getMessage(), null);
    }
}

Axios Login Function Part of PHP Collective 0

I'm working on an application that relies on Laravel Sanctum for login. However, after deploying and running the application on the server, I encountered an issue where, after a successful login, it doesn't redirect to the dashboard page. Instead, it redirects to a page with a **status code 302 **and remains on the login page. Additionally, I receive an email notifying me that I have successfully logged in.

Note: The code works on the local server without any issues.

Certainly, I will attach the codes for the routes and login.

API Routes :

Route::group(['prefix' => 'admin/auth'], function () { route::post('/login',[AuthController::class,'login'])->name('api_login'); Route::get('/logout', [AuthController::class, 'logout'])->name('api_logout'); });

Web Routes :

Route::middleware('auth:sanctum')->prefix('admin')->group(function (){ Route::get('/overview', [OverviewController::class, 'index'])->name('overview'); Route::get('/orders', [OrdersController::class, 'index'])->name('orders'); });

AuthController -> Login Function :

public function login(LoginRequest $request)
{
    try {
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            $user = Auth::user();
    
            if ($user->email_verified_at !== null) {
                // Generate a Sanctum token for the user
                $token = $user->createToken('auth-token')->plainTextToken;

                $ipAdress = $request->ipinfo->ip;
                //send login alert
                Mail::to($request->email)->send(new LoginAlert([
                    "CustomerName" => showUserName(),
                    "IpAdress"     => $ipAdress,
                    "Location"     => $request->ipinfo->country_name . ', ' . $request->ipinfo->city,
                    "BrowserOs"    => $request->header('User-Agent')
                ]));

                return ApiResponse::sendResponse(200, 'Authorized successfully', ['token' => $token]);
            }
            return ApiResponse::sendResponse(401, 'Email has not been verified', null);
        }
    
        return ApiResponse::sendResponse(401, 'Unauthorized', null);
    } catch (\Exception $th) {
        return ApiResponse::sendResponse(401, $th->getMessage(), null);
    }
}

Axios Login Function

function login() { document.getElementById("login-f").addEventListener("submit", function(event) { event.preventDefault(); }); let crsf_token = document.querySelector('meta[name="CRSF"]').getAttribute("content"); axios.defaults.headers.common['X-CSRF-TOKEN'] = crsf_token; const data = { email: document.getElementById('email').value, password: document.getElementById('password').value }; axios .post(/api/admin/auth/login, data, { responseType: "json" }) .then(function (response) { if (response.status === 200 && response.data.msg === "Authorized successfully") { setTimeout(function () { window.location.href = "/admin/overview"; }, 2000); } }

    })
    .catch(function (error) {
        // handle error
        console.log(error);
    });

}

I have tried changing the routes multiple times, but with no success! I attempted direct login using PHP, but encountered the same issue! I also tried sending header information: accept : application/json , content-type : application/json

0 likes
6 replies
vincent15000's avatar

If it works fine on localhost, that means that the problem is on the production server.

Is your production server a shared webhosting ?

Snapey's avatar

think you need to tidy up your question so that it can be taken seriously

1 like
Snapey's avatar

why are you using stateless api routes? How will the web route know you are authenticated?

1 like
krisi_gjika's avatar

Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs why are you guarding your web routes with sanctum? do your web routes return json?

1 like
Nourgeos's avatar
Nourgeos
OP
Best Answer
Level 1

After reviewing the code thoroughly and going through all the steps, I discovered the issue. I will share the solution with you so that anyone else facing the same problem can benefit:

The problem was in: config/sanctum.php

'stateful' => explode(',', env( 'SANCTUM_STATEFUL_DOMAINS', 'your-domain.com,subdomain.your-domain.com' )),

Unfortunately, the information was related to the local server, and I forgot to update it during the deployment process on the live server.

1 like

Please or to participate in this conversation.