Laravel custom middleware to secure ajax request

Ajax (Asynchronous JavaScript and XML), a tool used on the client side to create an asynchronous web applications. We use ajax in many scenarios. Ajax make javascript more fun. Some use case of Ajax can be :

Dynamically appending response’s ( Html Form/Or any element ) without loading the webpage.

ajax-example-one-laravel-nepal

When the + icon (Button) is clicked, rendering the table row with title and text element using ajax with html (table row) response.

Multilevel Menu or Categories where we need to get subcategory or sub menu by the menu or category id in the select box.

laravel-nepal-menu-ajax

When the menu section is selected, retrieving the parent for the menu using ajax.

Submitting the form using ajax

Well, the list will keep going. We have been doing this all the time. If we look at the console in network tab with xhr filter ( This will show only the xhr request’s ), we can see the ajax request there.

XHR request (XmlHttpRequest), is the name most browsers give the object used to send an Ajax request.

Now, if we click the link, we can see the response provided by the request on the next tab. I’ve seen many website’s out there which we can view the response directly on the new tab if it’s a GET method. I think it’s better we protect that from happening.

AjaxOnly Middleware

Let’s get started, we will be creating a simple middleware for protecting the ajax request. Let’s create a middleware, using a command php artisan make:middleware AjaxOnly .

The handle methods simply check if the request is ajax, if it is then the request will pass otherwise dump “This is not what we’re expecting :)” . I know we can make this more powerful by adding feature’s like checking the host as well and many other. Well, this is the first step and we will keep doing it more on upcoming article.

Usage for the middleware

We need to register the middleware first. Go to app/Http/Kernel.php and add at the last of $routeMiddleware

Now, we can use the middleware to the group of routes or route.

 

I hope this article was helpful for you. If any thing that i miss, feel free to drop in comments and happy coding 🙂

Sharing is caring!

Related Post