Security Tip: Validating User Input
[Tip#7] Always pass user input through a validator to ensure you only get the data you're expecting.
Greetings friends! It’s hard to believe but we’re already 2 months into Laravel Security in Depth! Today I’ve got one of my favourite tips: always pass user input through a validator. I talk about this one a lot, but it always deserves repeating.
Since this one has gone out to everyone, I want to remind all of the free subscribers to consider upgrading to a premium subscription. In our last In Depth email, we learnt about SQL Injection and had a lot of fun crafting real attacks on our interactive demo site (yep, you get to run your own SQLi attacks!). Next Week we’ll be looking at Escaping Output Safely, looking at different methods of escaping output in Laravel, including a few tricks for more complex data structures. Oh, and there are more fun interactive demos planned! (The demo site stays online, so you can subscribe and check it out at any time. I also provide access to the code, so you can run your own copy.)
Always Pass User Input Through a Validator
Don’t trust user input.
Don’t trust user input.
And one more for good measure…
Don’t trust user input.
You should always pass user input through a validator before you use it, and here are a few reasons why:
It forces you to define explicit rules which state exactly what sort of input is allowed in each field.
You’re far less likely to have unexpected data that causes your application to do unexpected things.
You have control over which fields are passed into a model for mass-assignment.
Your user interface can understand and display friendly errors to your users with minimal effort on your part.
Check out the docs for the many ways to use a validator in Laravel.
My preferred method is within controller actions on the Request
object, or using A FormRequest object for more complicated forms.
/**
* Store a new blog post.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validated = $request->validate([
'title' => ['required', 'unique:posts', 'max:255'],
'body' => ['required', 'string'],
'publish_at' => ['nullable', 'date'],
]);
// $validated contains only valid user input
$post = Post::create($validated);
// ...
}
Go forth and validate all the things! 😎
There are group subscriptions available, so you can easily sign up your whole team to the list! Plus you’ll be able to download and set up a local copy of our demo site in your own environment for everyone to explore and learn from.
Curious as to what validation strategy can be applied when saving input from a text editor (ie ckeditor, quill) that is html markup?
My initial thinking is that it would have to be a regex pattern that includes all the tags that are enabled, or something along those lines.