美文网首页
整合spatie/laravel-permission和lara

整合spatie/laravel-permission和lara

作者: liurongming | 来源:发表于2024-01-17 13:56 被阅读0次
    • 【可忽略,laravel10x版本已自带安装】安装:composer require spatie/laravel-permission和迁移php artisan migrate

    • 问题:There is no role namedwriterfor guardweb."

    • 解决:在User表中添加protected $guard_name ='sanctum';

    class User extends Authenticatable
    {
        use HasApiTokens, HasFactory, Notifiable;
        use HasRoles;
     
       protected $guard_name ='sanctum';
    
    }
    
    • 使用
      在Kernel.php中添加'check.permission'=>\App\Http\Middleware\CheckPermission::class,
     protected $middlewareAliases = [
            'check.permission'=>\App\Http\Middleware\CheckPermission::class,
     ];
    

    在route.php 下,添加 'check.permission'中间件,这样就可以统一认证。
    需要给每个路由命名name('user.info')

    Route::middleware(['auth:sanctum', 'check.permission'])->group(function () {
        Route::get('/user/info', [\App\Http\Controllers\Api\UserController::class, 'info'])->name('user.info');
        Route::get('/user/{uid}/info', [\App\Http\Controllers\Api\UserController::class, 'info'])->name('user.info');
    });
    

    中间件实现:
    核心代码就一句:$user->can($request->route()->getName())

    <?php
    
    namespace App\Http\Middleware;
    
    use App\Exceptions\ApiException;
    use Closure;
    use Illuminate\Http\Request;
    use Symfony\Component\HttpFoundation\Response;
    
    class CheckPermission
    {
        /**
         * Handle an incoming request.
         *
         * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
         */
        public function handle(Request $request, Closure $next): Response
        {
            $user = $request->user();
            if (!$user->can($request->route()->getName())) {
                throw new ApiException(__("http-statuses.403"), 403);
            }
            return $next($request);
        }
    }
    

    相关文章

      网友评论

          本文标题:整合spatie/laravel-permission和lara

          本文链接:https://www.haomeiwen.com/subject/cpilodtx.html