ggoran
ggoran

Reputation: 620

disable access to Laravel API from browser

How can I restrict direct access on GET route?

example localhost/api/helloworld

if I send a request with postman I want to get a response, but if I try open URL in a browser I need redirect to the homepage or give some 403 error?

should I use some header to restrict it or there is another way to do it in Laravel?

Upvotes: 1

Views: 3708

Answers (2)

Jaskaran Singh
Jaskaran Singh

Reputation: 914

use the following code to detect the requesting client from headers.

public function isBrowserRequest()
{
  $browsers = ['Opera', 'Mozilla', 'Firefox', 'Chrome', 'Edge'];

  $userAgent = request()->header('User-Agent');

  $isBrowser = false;

  foreach($browsers as $browser){
    if(strpos($userAgent, $browser) !==  false){
      $isBrowser = true;
      break;
    }
  }

  return ['result' => $isBrowser];
}

Upvotes: 0

Vijay
Vijay

Reputation: 96

The standard way to do this is use token. Laravel provides you API authentication, follow this link API Authentication (Passport)

Upvotes: 1

Related Questions