首页 > 解决方案 > 如何将用户类型的路由保护添加到具有 React 前端和 JWT 的 Laravel Web 应用程序?

问题描述

我正在制作一个 Laravel 应用程序,让教师可以对学生进行测试。我正在使用 React 前端,并且正在使用 JWT 对用户进行身份验证。我想按用户类型保护路线(例如,教师可以访问页面进行测试,而学生不能)。

通常,我可以做类似的事情

Route::middleware('jwt.auth')->get('users', function () {
    return auth('api')->user();
});

但我正在welcome.blade.php使用 React Router 将所有内容路由到我的和渲染路由。这就是我路由所有内容的方式:

Route::any('{all}', function () {
    return view('welcome');
})->where(['all' => '.*']);

我这样做是因为我注意到当我刷新不是根的路由时会出现 404 错误(例如,如果我刷新 /teacher-home 上的页面,我曾经得到 404)。我的问题是如何按用户类​​型保护我的路线,除了 /signin 和 /signup (希望这些不受保护,以便任何人都可以访问它们)?

这是我用于登录用户的代码:

public function login() {
        // get email and password from request
        $credentials = request(['email', 'password']);

        // try to auth and get the token using api authentication
        if (!$token = auth('api')->attempt($credentials)) {
            // if the credentials are wrong we send an unauthorized error in json format
            return response()->json(['error' => 'Unauthorized'], 401);
        }
        return response()->json([
            'token' => $token,
            'type' => 'bearer',
            'expires' => auth('api')->factory()->getTTL() * 60, // time to expiration

        ]);

这是我的用户迁移:

Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->enum('user_type', ['teacher', 'student']);
            $table->rememberToken();
            $table->timestamps();
        });

这是我所有路线的列表

<Route exact path='/' render={(pathName) => <Redirect to='/teacher-home'/>}/>
                        <Route exact path='/teacher-question-repo' render={(pathName) => <QuestionRepo path={pathName}/>}/>
                        <Route exact path='/teacher-home' render={(pathName) => <TeacherHome path={pathName}/>}/>
                        <Route exact path='/teacher-monitor' render={(pathName) => <TeacherMonitor path={pathName}/>}/>
                        <Route exact path='/teacher-tests' render={pathName => <TestRepo path={pathName}/>}/>
                        <Route exact path='/student-home' component={StudentHome}/>
                        <Route exact path='/student-test' render={() => <StudentTest testName="Normal Curves"/>}/>
                        <Route exact path='/edit-question/:item_id' component={EditQuestion}/>
                        <Route exact path='/teacher-tests/new-test' render={(pathName) => <TestForm path={pathName}/>}/>
                        <Route exact path='/teacher-tests/edit-test/:test_id' render={(pathName) => <TestForm path={pathName}/>}/>
                        <Route exact path='/signin' component={SignIn}/>
                        <Route exact path='/signup' component={SignUp}/>

标签: reactjslaraveljwt

解决方案


由于 react 正在处理您的路由,因此您不应在服务器端执行身份验证。

您可以使用自定义路由组件并在其中添加您的身份验证逻辑。看看下面的教程:
https ://tylermcginnis.com/react-router-protected-routes-authentication/


推荐阅读