0

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.

haberimyok
  • 13
  • 3

2 Answers2

0

Solution is:

New route in api.php:

Route::get("/unauthenticated", function(Request $request) {
    return response("Unauthenticated", 403);
})->name("unauthenticated");

Edit in Authenticate.php middleware:

    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            if($request->is("api/*")) {
                return route("unauthenticated");
            }
            return route('login');
        }
    }
haberimyok
  • 13
  • 3
0

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');
        }
    }
Mina Abadir
  • 2,951
  • 2
  • 15
  • 20