How to fix the Insecure Direct Object Reference Vulnerability in Laravel

Laravel
How to fix the Insecure Direct Object Reference Vulnerability in Laravel

Insecure Direct Object References occur when an application provides direct access to objects based on user-supplied input. As a result of this vulnerability, attackers can bypass authorization and access resources in the system directly, for example, database records or files.

Consider, User A uploaded a private photo at http://www.mysite/private/photo/5 and User B uploaded a photo at http://www.mysite/private/photo/6  (you should never use incremental ID’s in the URL in the first place, use some random keys. This is just an example to show the concept.)

Now User B shouldn’t be allowed to view the photo of User A at http://www.mysite/private/photo/5, but many developers miss to address this issue.

This is a common vulnerability that occurs in our projects due to lack of authorization. Most of the time we only check if a user is logged in to view the URL. A user can edit other users data by editing the URL. To prevent this we need to check if a user has access to edit these data.

Solution

The best method to prevent insecure direct object reference vulnerability in laravel is to use a middleware to check if the user has access to the object.

For the above private photo example, we can create a middleware named AccessPrivatePhoto and add this middleware to the route.

namespace App\Http\Middleware;

use Closure;
use App\Models\Photo;
use Auth;

class AccessPrivatePhoto
{
    /**
     * Handle an incoming request to whether the user has permissions to access a Photo
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::user()->role() != 'admin') {
            $photo = Photo::with('user')->find($request->photo);
            if($photo) {
                if($photo>user->id != Auth::id()) {
                    return redirect('/client/photos)->with('error', 'You do not have neccessary permissions to access the page');
                }
            }
        }

        return $next($request);
    }
}

This means if a user tries to enter a different URL when logged in it will be checked and if it doesn’t belong to them they are redirected.

Leave a Reply

Your email address will not be published. Required fields are marked *

one × 1 =

2hats Logic HelpBot