'Laravel - Jetstream - Routing authentication api/web

what i got:

  • created a new jetstream project (inertia) and Features::api() enabled in jetstream.php config,
  • web.php:
    Route::middleware(['auth:sanctum', 'verified'])->get('/testweb', function () {
        return "test web called";
    })->name('testweb');
    
  • api.php:
    Route::get('/testapi', function(){
        return 'api called';
    })->middleware('auth:sanctum');
    
  • also i created a test API token

now when I call /testweb in the browser and I am logged in I get "test web called"

when I am logged out and call it I get redirected to login view


when I make the API request WITH the token

I get the expected result "api called" BUT when I don't add a token to the request I don't get a 401 or so but I get a 200 with an "empty" view (with livewire i see it is the loginview, so i think with inertia it is the loginview too)


what is the cause o that? do i have to handle it myself? if yes, where and how??


additional note: I made the API request with POSTMAN, does it differ if I do not set the header as Accept: application/json?



Solution 1:[1]

When the request is made with that head included

Accept: application/json

then the Authenticate Middleware will know what to do and decide

if it will redirect it or

just send back a 401 response.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ben jamin