同一應用程式上的 Web 和 API 上的 Laravel 9 Auth 問題
P粉311617763
P粉311617763 2023-12-30 15:46:56
0
1
512

我正在嘗試在同一個 Laravel 應用程式中為 Web 和 API 建立身份驗證。但是網絡身份驗證無法正常工作...當我從.env 文件中刪除它時,我遇到了SESSION_DOMAIN 問題,然後兩個身份驗證都工作正常,但是當我將其保留到.env 文件中時,網絡身份驗證無法正常運作,收到419 |頁面過期錯誤。

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:ZSiB/A6U0zU8Vn2x8gbNnU1prcw90xQBfqm3JS9qp+I=
APP_DEBUG=true
APP_URL=http://localhost

SANCTUM_STATEFUL_DOMAINS=localhost:3000
SESSION_DOMAIN=localhost

LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=xpert_test
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=cookie
SESSION_LIFETIME=120

MEMCACHED_HOST=127.0.0.1

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

這是我的 .env 檔案程式碼

<?php

namespace AppHttpControllersAPI;

use AppHttpControllersController;
use AppModelsUser;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesHash;
use IlluminateSupportFacadesValidator;

class UserController extends Controller {
    // user registration
    public function register(Request $request) {

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|unique:users,email',
            'password' => 'required|string|min:6',
            'cpassword' => 'required|string|min:6|same:password',
        ], [
            'cpassword.same' => 'Password confirmation does not match.',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors' => $validator->errors()
            ], 200);
        }

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'role' => 0
        ]);
        $request->session()->regenerate();
        return response()->json([
            'success' => true,
            'user' => $user,
            'token' => $user->createToken('API Token')->plainTextToken
        ], 200);
    }

    // user login
    public function login(Request $request) {
        $validator = Validator::make($request->all(), [
            'email' => 'required|string|email',
            'password' => 'required|string|min:5'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'validationError' => true,
                'message' => $validator->errors()
            ], 200);
        }

        $creditentials = [
            'email' => $request->email,
            'password' => $request->password,
            'role' => 0
        ];

        if (!Auth::attempt($creditentials)) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid credentials'
            ], 200);
        }
        $user = User::where('email', $request->email)->first();
        $request->session()->regenerate();
        return response()->json([
            'success' => true,
            'user' => Auth::user(),
            'token' => $user->createToken('API Token')->plainTextToken
        ], 200);
    }

    // user profile
    public function profile() {
        return response()->json([
            'success' => true,
            'user' => Auth::user()
        ], 200);
    }

    public function logout(Request $request) {
        $request->user()->tokens()->delete();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return response()->json([
            'success' => true,
            'message' => 'User loggedOut successfully'
        ], 200);
    }
}

這是我的 API 授權程式碼

<?php

namespace AppHttpControllers;

use AppModelsProduct;
use AppModelsQuestion;
use AppModelsSection;
use AppModelsTest;
use IlluminateHttpRequest;

class AuthController extends Controller {

    // view login page
    public function index() {
        return view('index');
    }

    // view dashboard page
    public function adminDashboard() {

        $products_count = Product::count();
        $sections_count = Section::count();
        $tests_count = Test::count();
        $questions_count = Question::count();
        return view('admin.dashboard', [
            'products_count' => $products_count,
            'sections_count' => $sections_count,
            'tests_count' => $tests_count,
            'questions_count' => $questions_count,
        ]);
    }

    // handle admin login
    public function adminLogin(Request $request) {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required|max:50|min:5'
        ]);
        $credentials = $request->only(['email', 'password']);
        if (auth()->attempt($credentials)) {
            $request->session()->regenerate();
            if (auth()->user()->role === 1) {
                return redirect()->route('admin.dashboard');
            }
            // else {
            //     return redirect()->route('super.dashboard');
            // }
        }
        return redirect()->back()->withErrors(['message' => 'Invalid credentials']);
    }

    // handle admin logout
    public function logout(Request $request) {
        auth()->logout();
        $request->session()->invalidate();
        return redirect()->route('admin.login.page');
    }
}

這是我的網路身份驗證程式碼

Route::middleware('guest')->group(function () {
  Route::get('/', [AuthController::class, 'index'])->name('admin.login.page');
  Route::post('/admin-login', [AuthController::class, 'adminLogin'])->name('admin.login');
});

Route::middleware('auth')->group(function () {
  Route::get('/logout', [AuthController::class, 'logout'])->name('logout');
  Route::get('/dashboard', [AuthController::class, 'adminDashboard'])->name('admin.dashboard');
});

這是我的 web.php 路由檔案

Route::prefix('v1')->group(function () {
    // unprotected routes
    Route::post('/login', [UserController::class, 'login']);
    Route::post('/register', [UserController::class, 'register']);

    // protected routes
    Route::middleware(['auth:sanctum'])->group(function () {
        Route::get('/profile', [UserController::class, 'profile']);
        Route::post('/logout', [UserController::class, 'logout']);
    });
});

這是 api.php 檔案程式碼

P粉311617763
P粉311617763

全部回覆(1)
P粉818561682

分享更多程式碼。

Laravel 中的 419 個錯誤頁面通常與 CSRF 相關,哪個請求可能會被視為跨站請求偽造攻擊。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板