简体   繁体   English

授权 function 不使用中间件 | Laravel

[英]Authorize function is not working with middleware | Laravel

I have an authorization using middleware where Function could only run when authorized我有使用中间件的授权,其中 Function 只能在授权时运行

this is my middleware:这是我的中间件:

class IsAdmin
{
    public function handle($request, Closure $next)
    {
        if (auth()->check() && auth()->user()->is_admin == 1) {
            return $next($request);
        }

        return abort(403, 'Forbidden');
    }
}

my Controller:我的 Controller:

public function destroy(int $bookId, int $reviewId, Request $request)
{
    // @TODO implement

    $check_bookReview = BookReview::firstWhere('id', $reviewId)->where('book_id', $bookId);
    if ($check_bookReview && isAdmin()) {
        BookReview::destroy($reviewId);
        return response()->noContent();
    } else {
        abort(404);
    }
}

and my api.php as well my Kernel :和我的api.php以及我的Kernel

'auth.admin' => \App\Http\Middleware\IsAdmin::class

Route::group(['middleware' => ['auth.admin']], function (){
Route::post('/books', 'BooksController@store');
Route::post('/books/{id}/reviews', 'BooksReviewController@store');
Route::delete('/books/{bookId}/reviews/{reviewId}', 'BooksReviewController@destroy');
});

and i have a User db field where it contains api_token and is_admin like below:我有一个User数据库字段,其中包含api_tokenis_admin如下所示: 用户数据库

and my Postman still return 403 forbidden while i already gave an authorization by headers:我的 Postman 仍然返回 403 禁止,而我已经通过标题授权: 邮差

what should i do here, to fulfill my function?我应该在这里做什么来完成我的 function?

Looks like your Authenticate middleware is not working, so it likely fails on auth()->check() .看起来您的Authenticate中间件不起作用,因此它可能在auth()->check()上失败。

Make sure to use the auth middleware from Laravel, you can also use a guard as described here: https://laravel.com/docs/9.x/authentication#protecting-routes确保使用来自 Laravel 的auth中间件,您也可以使用此处所述的保护: https://laravel.com/docs/9.x/authentication#protecting-routes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM