簡體   English   中英

使用 Laravel 保護內部 API 端點

[英]Securing internal API endpoint with Laravel

我有一個 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', 'Api\DocumentsController')->middleware('ajax')->only(['show']);

如您所見,我有一個名為ajax的自定義中間件。 這確保只接受對 API 端點的 AJAX 請求:

app\Http\Middleware\RequestIsAjax.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);
}

或者,您也可以在查找文檔時執行此操作(因為您似乎沒有使用 Model 綁定),因此這也應該有效:

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);
}

再說一次,您不僅可以在 controller 中實現它,還可以在中間件、表單請求等中實現它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM