Unexpected 302 redirect after success login using Laravel Sanctum

223 Views Asked by At

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

1

There are 1 best solutions below

0
On

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.