バックエンド・ショーツ
HTTPリクエストからの入力など、信頼されていないデータを処理するたびに、Webアプリケーションのバックエンドで完全に検証する必要があります.
一般的に要求オブジェクトから
ユーザ入力に関しては、パラノイアである. は常にバックエンドで検証します.フロントエンドの検証は、UXにとって良いですが、保護を提供しません. 要求されていないデータを直接読み取ろうとするのを避ける. からのFilip OlsokによるPexels写真
時々、信頼できない入力データはレーダーの下で飛びます.このための一般的な例は、フィールドに到達するために最初にCSVコンテンツを解析する必要があるCSVインポートです.それにもかかわらず、解析されたデータを検証することが重要です.
function store(Request $request)
{
$validated = $this->validate($request, [
'name' => 'required|string|max:255',
'unit_price' => 'required|int|min:0|max:10000',
'currency' => 'required|in:USD,EUR',
'stock' => 'required|int|min:0|max: 1000000',
]);
$product = new Product($validated);
$product->save();
return redirect()->route('products.show', ['product' => $product->id]);
}
laravelのリクエストデータを読む最も簡単で安全な方法の一つは、コントローラ内の$this->validate
関数です.有効なデータ(有効なデータのみ)を含む配列を返します.エラーが発生した場合はValidationException
をスローします.一般的に要求オブジェクトから
$request->get('field')
または同様の方法で直接データを読むのを避けるべきです.なぜなら、必要な妥当性検査を追加するのを忘れるのはとても簡単です.リクエストオブジェクトから直接データを読むのはコード臭いです.持ち帰り
ボーナス
時々、信頼できない入力データはレーダーの下で飛びます.このための一般的な例は、フィールドに到達するために最初にCSVコンテンツを解析する必要があるCSVインポートです.それにもかかわらず、解析されたデータを検証することが重要です.
public function importStore(Request $request)
{
// Validate the file metadata.
$file = $this->validate($request, [
'file' => 'required|file|mimes:txt,csv|max:5120',
])['file'];
// Load CSV.
$csv = Reader::createFromPath($file->path());
$csv->setHeaderOffset(0);
$header = $csv->getHeader();
$input = iterator_to_array($csv->getRecords(), false);
// Set a limit for the maximum number of products per import.
if (count($input) > 1000) {
throw ValidationException::withMessages([
'file' => 'The import is limited to 1000 rows.',
]);
}
// Do a quick check to see if the header is correct. Although the
// validation logic further below would also find the error, it
// would produce multiple error messages for each line in the file.
if ($header !== ['name', 'unit_price', 'currency', 'stock']) {
throw ValidationException::withMessages([
'file' => 'The CSV file does not have the right header.',
]);
}
// Validate CSV file content.
$validated = Validator::make($input, [
'*' => 'required|array',
'*.name' => 'required|string|max:255',
'*.unit_price' => 'required|int|min:0|max:10000',
'*.currency' => 'required|in:USD,EUR',
'*.stock' => 'required|int|min:0|max: 1000000',
])->validate();
$instant = now();
foreach ($validated as &$entry) {
$entry['created_at'] = $instant;
$entry['updated_at'] = $instant;
}
Product::insert($validated);
return redirect()->route('products.index');
}
Reference
この問題について(バックエンド・ショーツ), 我々は、より多くの情報をここで見つけました https://dev.to/hbgl/backend-shorts-validate-all-your-inputs-2ffhテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol