1
votes

I am building an api driven Laravel 5.5 app. I want to use the publicly accessible api to process the UI driven requests as well.

My question is, in my api auth middleware, what is the best way to detect a UI driven requests (ajax requests) and allow it to pass through without trying to validate api auth credentials? (maybe try to validate csrf token?)

2
Are you using Laravel Passport? - The Alpha

2 Answers

2
votes

You can use a middleware to add additional checking for CSRF tokens although Laravel does that by default on web routes (Doc).

for example add this Middleware for preventing accessing from anything but ajax: run this command:

php artisan make:middleware AllowOnlyAjaxRequests

Then in the middleware file:

    namespace App\Http\Middleware;

    use Closure;

    class AllowOnlyAjaxRequests
    {
        /**
        * Handle an incoming request.
        *
        * @param  \Illuminate\Http\Request  $request
        * @param  \Closure  $next
        * @return mixed
        */
        public function handle($request, Closure $next)
        {
            if(!$request->ajax()) {
                // Handle the non-ajax request
                return response('', 405);
            }

            return $next($request);
        }
    }    

and then Add 'ajax' => \App\Http\Middleware\AllowOnlyAjaxRequests::class, to your routeMiddleware array in app/Http/Kernel.php

(Middleware Docs)

for detecting a request is sent via ajax you can use $request->ajax() code. And if you want to exclude some URIs from validating CSRF (Do that with caution) you can do this.

0
votes

You can exclude specific routes from checking csrf token in VerifyCsrfToken middleware.

After excluding it while validating request in your controller, You can validate csrf token if $request->ajax() returns false.

You can validate csrf by using Session::token() or csrf_token() function.

Hope this will help you.