Laravel 8 -> 与 JWT 和邮递员的授权



我正在用Laravel8构建一个API,并使用poster。此外,我使用JWT进行身份验证,并希望授权创建新帖子,我希望只有当用户是管理员或作者时才能创建新帖子。因此,我创建了一个中间件AdminLevelAuthorization,并在内核中将其添加为'auth.level'

所以我把这个用于路由的中间件放在api.php中:Route::apiResource('posts' , PostController::class)->middleware('auth.level:admin,author');

在邮差中,我登录并保存了我的令牌,我只是不知道如何使用此令牌进行授权

当我在邮递员和授权部分走到这条路线http://localhost:8000/api/posts时,承载令牌类型我在令牌字段中输入我的令牌,所以它说:"You are unauthorized to access this resource"

我不知道我输入令牌是否错误,或者我的中间件是的问题

这是我的中间件:

class AdminLevelAuthorization
{
public function handle($request, Closure $next, ...$levels)
{
try {
//Access token from the request    
$token = JWTAuth::parseToken();//Try authenticating user
$user = $token->authenticate();
} catch (TokenExpiredException $e) {
//Thrown if token has expired
return $this->unauthorized('Your token has expired. Please, login again.');
} catch (TokenInvalidException $e) {
//Thrown if token invalid
return $this->unauthorized('Your token is invalid. Please, login again.');
} catch (JWTException $e) {
//Thrown if token was not found in the request.
return $this->unauthorized('Please, attach a Bearer Token to your request');
}
//If user was authenticated successfully and user is in one of the acceptable levels, send to next request.
if ($user && in_array($user->levels, $levels)) {
return $next($request);
}
return $this->unauthorized();
}
private function unauthorized($message = null){
return response()->json([
'message' => $message ? $message : 'You are unauthorized to access this resource',
'success' => false
], 401);
}
}

谢谢你的帮助:(

问题出现在s中,对于user->levels,它必须是$user->level

最新更新