使用 Laravel 保护内部 API 端点



我有一个Web应用程序,用户可以在其中上传文档。

用户可以上传许多文档(hasMany(。

我在下面Vue文件,它获取我的内部 API 以从上传的文档获取信息。以下是我正在使用的方法:

ShowDocument.Vue

getDocument: function (documentId) {
axios.get('/api/documents/' + documentId).then((response) => {
this.document = response.data.document;
}).catch(error => {
console.log(error);
})
},

在我的routes/api.php文件中,我定义了以下路由:

Route::apiResource('documents', 'ApiDocumentsController')->middleware('ajax')->only(['show']);

如您所见,我有一个名为ajax的自定义中间件。这可确保仅接受对 API 端点的 AJAX 请求:

appHttpMiddlewareRequestIsAjax.php

public function handle($request, Closure $next)
{
if (! $request->ajax())
return abort(403);
return $next($request);
}

此外,DocumentsController看起来很简单:

public function show($id)
{
$document = Document::findOrFail($id);
return response()->json([
'document' => $document,
], 200);
}

目前为止,一切都好。现在,我的问题是 - 此 API 端点仅在内部使用(目前(,但作为用户,我可以通过简单地将 AJAX 请求发送到以下位置来轻松查看其他用户文档的信息:

/api/documents/<documentID>

并简单地替换为另一个数字。

我的问题是,如何防止这种情况并确保只有用户可以查看自己的文档?

您可以添加额外的检查。它可以像这样简陋:

public function show($id)
{
$document = Document::findOrFail($id);
if ($document->user_id !== auth()->id())
{
return response()->json([
'message' => 'You are not allowed to see this document',
], 403);
}
return response()->json([
'document' => $document,
], 200);
}

或者,您也可以在查找文档时执行此操作(因为您似乎没有使用模型绑定(,因此这也应该有效:

public function show($id)
{
$document = Document::where('user_id', auth()->id)->find($id);
if ($document)
{
return response()->json([
'message' => "The document does not exist or you are not allowed to see it.",
], 404);
}
return response()->json([
'document' => $document,
], 200);
}

再说一次,您不仅可以在控制器中实现这一点,还可以在中间件、表单请求等中实现这一点。

最新更新