0

I'm very new to laravel and created my first REST api project with it, then I set cors middleware and it works perfectly, one thing is so important to me, that prevent open route with GET method in browser directly, I don't know how to allow api return data only when it called form my own website not directly in browser. I googled and found this solution

public function handle($request, \Closure $next)
    {
        if ( ! $request->ajax())
            return response('Forbidden.', 403);

        return $next($request);
    }

So it works fine and if you open route in browser directly like site.com/api/car/index it return 403 error, but it return this error in my website too! my website created with reactjs/nextjs and use axios to call api, any idea how to fix this? or is there better solution to avoid this problem?

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Jack The Baker
  • 1,781
  • 1
  • 20
  • 51

1 Answers1

2

in this case will recommend to look towards the next solution:

function handle(\Illuminate\Http\Request $request, \Closure $next)
{
    $allowedList = env('allowed_user_agents');
    if (! in_array($request->userAgent(), $allowedList, true)) {
        return response('Forbidden.', 403);
    }

    return $next($request);
}

This is base idea, but should work for your problem :)

UPD:

More fluent solution:

function handle(\Illuminate\Http\Request $request, \Closure $next)
{
    $allowedList = env('allowed_user_agents', ['PostmanRuntime/7.29.0']);
    if (! in_array($request->userAgent(), $allowedList, true)) {
        return abort(\Illuminate\Http\Response::HTTP_FORBIDDEN);
    }

    return $next($request);
}

UPD2: Taking into account the feedback from comments. Add env variable which will represent user agent name of your FE application.

ALLOWED_USER_AGENT='Fe SPA client'

Add it config, in my case i am using config/cors.php:

'allowed_user_agent' => env('ALLOWED_USER_AGENT', 'default-name')

Middleware:

function handle(\Illuminate\Http\Request $request, \Closure $next)
{
    $spaUserAgent = config('cors.allowed_user_agent');
    
    if ($request->userAgent() !== $spaUserAgent) {
        return abort(\Illuminate\Http\Response::HTTP_FORBIDDEN);
    }

    return $next($request);
}

Axios config:

axios
    .get(requestUrl, {
        headers: {
            'User-Agent': 'Fe SPA client'
        }
    })