laravel / sanctum

Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.
https://laravel.com/docs/sanctum
MIT License
2.75k stars 296 forks source link

Handle JSON Response in guest Middleware - RedirectIfAuthenticated out of the box #518

Closed Gkiokan closed 4 months ago

Gkiokan commented 5 months ago

Hi guys,

I love the way that sanctum makes our live easy, but the latest L11 changes makes it a bit hard to modify the behavior of json Requests when it comes to sanctum usage for api only based Projects with dedicated SPA Frontends.

We were used to modify the RedirectIfAuthentication Middleware before with our if statement but now this takes a bit more effort.

Starting Point Environment

Fresh Laravel 11 Installation with php artisan install:api for api only usage.

The Problem

RedirectIfAuthenticated Middleware is returning the home Route Response when guest Middleware takes affect. Happend to me when I tested subsequent Requests to the login route. First Request gone though, 2nd redirected to home. Even Accept and Content-Type Headers were set accordingly.

Expected Behavior

When doing JSON Requests, return a 403 Already Authenticated JSON Response.

The Solution

Creating a custom Middleware and override the guest Middleware as described on my SO Answer

The Question

Sanctum do have a fallback for checking the Authenticated User based on the Bearer token, but why doesn't the RedirectIfAuthenticated Middleware checks for that, too?

driesvints commented 4 months ago

Thank you for your suggestion. Right now we don't have time to dig deeper into this unfortunately. Should you come up with a PR to solve this we'd gladly take a look.

Tamas-hi commented 2 months ago

This has come up a few times, most notably here: https://github.com/laravel/laravel/pull/6229

Up until now it was always 'add it to your own app if you like', but I might prepare another PR explaining why (imo) would really make sense to be integrated in Laravel. Though this would rather fit to laravel/framework, and not here in the Sanctum repo.