Laravel Public Routing - Bypass CSRF and CORS

By default, all routes in Laravel require CSRF and CORS protection, which makes obvious sense. Occasionally, we need to bypass that for specific routes in your application; here's how I did it.


At TheReverseCalculator.com, I needed the forms to be accessible from websites outside of the base domain, since that's how the whole application works. So first I started off by modifying the RouteServiceProvider this way:

    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapApiRoutes();
        $this->mapWebRoutes();
        $this->mapPublicRoutes();
    }

    ...

    /**
     * Define the "public" routes for our application
     *     These routes circumvent all the csrf checks;
     *     they are served outside of application domain.
     */
    protected function mapPublicRoutes()
    {
        Route::group([
            'middleware' => 'public',
            'namespace' => $this->namespace,
        ], function($router) {
            require base_path('routes/public.php');
        });
    }

This allows us to have a new file called public.php in the routes folder where we can store all of our publicly-accessible routes. These routes, and only these routes, circumvent all the domain protections, so we definitely need to be careful what we allow in these controllers.

There are two pieces that get referenced above that need to be created: the routes/public.php file (obviously), and a new middleware called public. Head over to app/Http/Kernel.php and reference the middleware there:

    'public' => \App\Http\Middleware\AllowAccessFromAnywhere::class

and then create the middleware, like this:

<?php

namespace App\Http\Middleware;

use Closure;

class AllowAccessFromAnywhere
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, X-Requested-With, Origin')
            ->header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    }
}

So the middleware disables the CORS built-in to Laravel. One big thing to notice is the 'Access-Control-Allow-Methods' line: TheReverseCalculator needs to have access to GET and POST, but not PUT, DELETE, etc. We'll set this to limit routes to only what's absolutely necessary.

...and that's it! Any routes added to routes/public.php file bypass any domain protection to be accessible from anywhere. Obviously be very careful with this, but if you have a website that needs public access, it's a quick and easy way to enable it.

{{ message }}

{{ 'Comments are closed.' | trans }}