此页面无法正常工作127.0.0.1 已重定向您太多次

问题描述 投票:0回答:1

我想创建中间件,当我想访问网站页面时,我必须首先进行第二次登录,如果我没有令牌,则页面将重定向到登录页面。我将代码输入到中间件中,但网站上显示的是错误 ** “此页面无法正常工作127.0.0.1 已将您重定向了太多次。 尝试删除您的 cookie。 ERR_TOO_MANY_REDIRECTS“**

在我的终端中,第二个登录页面上发生了循环。我正在使用 Laravel 11

这是我的控制器代码

public function showLoginForm()
    {
        $pageTitle = 'LOGIN';
        return view('auth.login', ['pageTitle' => $pageTitle]);
    }

    // Handle the login request
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        $response = Http::withOptions(['verify'=> false])
        ->post('MYAPI/LOGIN', [
            'email' => $request->email,
            'password' => $request->password,
        ]);

        Log::info('Login response:', $response->json());

        if ($response->successful()) {
            $token = $response['token'];
            session(['api_token' => $token]);
            return redirect()->route('login-second');
        }

        return back()->withErrors(['login' => 'Email atau password salah']);
    }

    // Get token for SSO
    private function get_token()
    {
        $response = Http::WithOptions(['verify' => false])
        ->post('MYAPI/LOGIN', [
            'email' => 'MYEMAIL',
            'password' => 'MYPASSWORD',
        ]);

        $res = $response->json();
        return $res['token'] ?? null;
    }

    // Display the second login form
    public function showSecondLoginForm()
    {
        $token = $this->get_token();
        return view('auth.login-second', ['token' => $token]);
    }

    public function showSecondLoginFormx(){
        echo "TEST";
        // return view('coba');
    }

    public function secondLogin(Request $request)
    {
        $token = $this->get_token();
        $response = Http::withOptions(['verify'=>false])
        ->withToken($token)
        ->post('MYAPI/LOGIN-SECOND', [
            'username' => $request->username,
            'password' => $request->password,
            'token' => $token
        ]);
        Log::info('Second login response:', $response->json());
        $data = $response->json();

        if (isset($data['data'])) {
            if ($data['data']['login'] == true) {
                session([
                    'sso_data' => $data['data'],
                ]);
                return redirect()->route('dashboard')->with('success', $data['data']['message']);
            } else {
                return redirect()->back()->withErrors(['secondlogin' => $data['data']['message']]);
            }
        }

        return redirect()->back()->withErrors(['secondlogin' => 'Invalid response from SSO service.']);
    }

这是我的路线

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
use App\Http\Middleware\EnsureSecondLogin;

// Rute yang tidak memerlukan autentikasi
Route::get('/', function () {
    return view('welcome');
});

// Login
Route::get('/login', [AuthController::class, 'showLoginForm'])->name('login');
Route::post('/login', [AuthController::class, 'login']);

// Login kedua
Route::get('/login-second', [AuthController::class, 'showSecondLoginForm'])->name('login-second');
Route::post('/login-second', [AuthController::class, 'secondLogin'])->name('login-second.submit');

// Rute yang memerlukan autentikasi
Route::middleware([EnsureSecondLogin::class])->group(function () {
    Route::post('/search', [AuthController::class, 'search'])->name('search');
    Route::get('/dashboard', [AuthController::class, 'dashboard'])->name('dashboard');
    Route::get('/profile', [AuthController::class,'profile'])->name('profile');
    Route::get('/pegawai', [AuthController::class,'pegawai'])->name('pegawai');
    Route::post('/cari-pegawai', [AuthController::class, 'searchPegawai'])->name('cari-pegawai');
    Route::get('/api/profil-pegawai/{nip}', [AuthController::class, 'getProfile']);
    Route::get('/api/profile/{nip}', [AuthController::class, 'getProfileByNip'])->name('profile.by.nip');
    Route::get('/change-password', [AuthController::class, 'showChangePasswordForm'])->name('show-change-password-form');
    Route::post('/change-password', [AuthController::class, 'changePassword'])->name('change-password');
    Route::post('/logout', [AuthController::class, 'logout'])->name('logout');
    Route::get('/coba',[AuthController::class, 'coba'])->name('coba');
});

Route::get('/coba',[AuthController::class, 'coba'])->name('coba');

这是我的中间件

class EnsureSecondLogin
{
    // File: app/Http/Middleware/EnsureSecondLogin.php

    public function handle(Request $request, Closure $next)
    {

        if (!$request->session()->has('api_token')) {
            return redirect('/login');
        }

        if (!$request->session()->has('sso_data')) {
            return redirect('/login-second');
        }

        return $next($request);
    }

和我的app.php

    ->withMiddleware(function (Middleware $middleware) {
        $middleware->web(append: [
            EnsureSecondLogin::class
        ]);
    })

访问网站时不会出现重复的同一页面,并且可以使用中间件进行登录过程

laravel loops laravel-middleware laravel-11
1个回答
0
投票

您已在函数

app.php
中添加了
withMiddleware
中的中间件,这意味着它将运行于
web.php
中的每条路线,甚至是
/login
中。这会导致重定向循环。在
Route::middleware([EnsureSecondLogin::class])
中使用
routes/web.php
就足够了。

© www.soinside.com 2019 - 2024. All rights reserved.