2 回答

TA貢獻1719條經驗 獲得超6個贊
中間件的更新版本是:
class SuperuserAuthorization{
public function __invoke(Request $request, RequestHandler $handler): Response{
$authorization = explode(" ", $request->getHeader('Authorization')[0]);
$user = User::getUserByApiKey($authorization[1]);
if(! Role::isSuperuser($user)){
$response = new Response();
return $response->withStatus(403);//Forbidden
}
return $handler->handle($request);
}
}

TA貢獻1790條經驗 獲得超9個贊
路由中間件難道不應該阻止請求進入應用程序并立即返回403嗎?
Slim 4 使用 PSR-15 兼容中間件。在PSR-15元文檔中有一個很好的例子來說明如何實現授權中間件。如果您不希望進一步處理請求,則需要避免調用。$handler->handle($request)
正如您在示例中看到的,如果請求未獲得授權,則返回與 返回值不同的響應。這意味著你的觀點是說:$handler->handle($request)
我知道我可以創建狀態為403的新空響應,因此數據不會出來,但關鍵是請求永遠不應該超出這個中間件
在某種程度上是正確的,但是您應該通過在調用處理程序之前返回適當的響應來防止請求進一步發展,或者引發異常并讓錯誤處理程序處理它。
下面是一個簡單的中間件,它隨機授權一些請求,并為其他請求拋出一個異常:
$app->group('/protected', function($group){
$group->get('/', function($request, $response){
$response->getBody()->write('Some protected response...');
return $response;
});
})->add(function($request, $handler){
// randomly authorize/reject requests
if(rand() % 2) {
// Instead of throwing an exception, you can return an appropriate response
throw new \Slim\Exception\HttpForbiddenException($request);
}
$response = $handler->handle($request);
$response->getBody()->write('(this request was authorized by the middleware)');
return $response;
});
要查看不同的響應,請訪問路徑幾次(請記住中間件是隨機操作的)/protected/
- 2 回答
- 0 關注
- 192 瀏覽
添加回答
舉報