Search code examples
laravellaravel-7laravel-airlock

Laravel Airlock how to return different responses for unauthenticated web and api requests


I am developing a mobile app and website with laravel + react native.

When you send a request to a route with "auth:airlock" middleware, If you pass wrong Bearer token it redirects you to /login page. I want to return response("Unauthenticated", 403). But, at the same time I want to keep redirecting unauthenticated users to /login page for my web users.

So I want to achieve:

  • When an unauthenticated web users try to browse: domain.com/settings, he will redirected to domain.com/login page.

  • When a request comes to domain.com/api/settings, if requests does not have Bearer token or has wrong Bearer token, response will be json.


Solution

  • I would say the cleanest solution to that, is to send the request from your React Native as ("application/json"). In that case, Laravel will determine it's an API call, and will not redirect to route("login")

    Here is an excerpt from App\Http\Middleware\Authenticate:

    /**
         * Get the path the user should be redirected to when they are not authenticated.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return string|null
         */
        protected function redirectTo($request)
        {
            if (! $request->expectsJson()) {
                return route('login');
            }
        }