-
【可忽略,laravel10x版本已自带安装】安装:
composer require spatie/laravel-permission
和迁移php artisan migrate
-
问题:
There is no role named
writerfor guard
web."
-
解决:在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);
}
}
网友评论