如何使用 Laravel 和 jwt-auth 保护来自非管理员用户的 api 路由

How to protect api routes from users who are not admins using Laravel and jwt-auth

我是 Laravel 和 Whosebug 的新手,所以如果我的问题格式不正确,我深表歉意。任何有关此的提示将不胜感激。

我最近设法使用 jwt-auth 在我的 Laravel API 上实现了令牌身份验证。

我能够使用 jwt-auth 中间件保护我的 api 路由,以确保特定用户已收到令牌(已登录)。

  Route::group(['middleware' => ['jwt.auth']], function() {

  // List Books
  Route::get('books', 'BookController@index');

  )};

JWT 是在我创建的名为 APILoginController 的控制器中创建的,它包含:

    public function login(Request $request)
{

    // check the users credentials
    $credentials = $request->only('email', 'password');
    try {
        if (! $token = JWTAuth::attempt($credentials)) {
            return response()->json(['error' => 'Invalid Credentials'], 401);
        }
    } catch (JWTException $e) {
        return response()->json(['error' => 'could_not_create_token'], 500);
    }
    // the users credentials are correct - return web token
    $user = Auth::user();

    return response()->json(compact('token', 'user')) ;
}

我已经为我的用户添加了一个 is_admin 字段 table

  Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('is_admin');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

我希望我能够使用此字段来保护某些路由免受普通用户的访问,其中 is_admin = 0 并且只允许管理员 (is_admin = 1) 访问它们。我不知道这是否是解决此问题的正确方法,但它似乎是最简单的。

任何帮助或指导将不胜感激,因为我已经为此苦苦挣扎了一段时间。我遇到的大多数教程似乎都创建了另一个 table 角色,但这对于我的技能水平和我正在尝试创建的应用程序来说似乎有点过分和复杂。

亲切的问候, 马修

您需要做的是编写自己的中间件来检查用户是否是管理员

php artisan make:middleware checkAdmin

此命令将在您的 app/Http/Middleware 目录中放置一个新的 CheckAdmin class

<?php

namespace App\Http\Middleware;

use Closure;

class checkAdmin
{

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

           //get admin value of user from database

           if ($adminValue != 1) {
               return redirect('home');
           }

           return $next($request);
     }

}

现在将您的中间件添加到所有管理员专用路由

Route::get('admin/profile', function () {
   //
})->middleware(CheckAdmin::class);

有关 Laravel 中的中间件的更多信息,请参阅文档 https://laravel.com/docs/5.6/middleware

我通常使用 Laravel 附带的 Passport,但我认为它非常相似。

您可以创建一个自定义中间件来验证哪种类型的用户正在尝试访问端点。在你的例子中,它会验证用户是否是 is_admin => 1。你会有这样的东西:

Route::group(['middleware' => ['jwt.auth', 'is_admin']], function() {

您的另一个选择是在用户首次请求时为您的令牌定义一个范围。我不知道 jwt-auth 是否可行,但你会得到这样的结果:

->middleware('scopes:admin');

希望对您有所帮助!