phplaravelpython-requestscorsmiddleware

Is this safe when it come to prevent requests from outside the own website?


I am intending to specify the single origins where I want my different endpoints to receive requests from. After looking at different options I thought that this might be the simplest way, and it seems safe, but is it? Also, can the request origin be faked to emulate the web origin?

public function handle($request, Closure $next)
{
   $requestHost = parse_url($request->headers->get('origin'), PHP_URL_HOST);
   if ($requestHost != env('APP_URL')) {
         return response()->json('Wrong Origin Mate', 200);  
   } else {
         return $next($request);
    }
}


Solution

  • Short answer is: no, its not reliable for security.

    The reason is that the Origin header (and similarly the Referer header) can be easily spoofed by clients.... Hackers these days using tools like Postman, Curl or custom Scripts can set any value for the Origin header.

    These request origin can be faked like this for example.

    curl -H "Origin: https://your_domain_ofc.com" ``https://yourendpoint.com/api

    So, you should use authentication and authorization (API keys, OAuth tokens, JWT or stmh)

    Furthermore, your code returns a 200 status code for a failed origin check, use 403 Forbidden for best practise.

    I really hope this helped you at least a little bit, here are some links if you want to read it yourself.

    https://owasp.org/API-Security/

    https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Authentication

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS