TS1997's avatar
Level 1

API with stateful and stateless auth

Hello,

I'm currently building an API using Laravel 11, Breeze and Sanctum. I have a React frontend that uses the built in web authentication for viewing the user profile, generating api tokens etc. I also have an API that users will be able to use externally in their own applications. I also have my own implementation of this API in my React frontend.

I want to add a custom authentication type/middleware for the API routes that makes authentication using their bearer token required when accessed externally. This is the default behavior of the auth:sanctum middleware. I do, however, also want to have optional authentication using the default web auth when accessing the API using my own frontend.

My goal, in other words, is to be able to get the logged in user from the stateful web auth when accessing API routes with my own frontend. This auth shouldn't be required as the users doesn't have to be logged in in order to use my frontend. I do, however, want required bearer token authentication for the API routes when accessed externally from users applications etc.

One solution for this would be to set up two different sets of endpoints, one for my frontend and one for the API but I would prefer to combine everything into a single set of endpoints for maintainability and for some logic within the API functionality. Is this possible in a neat way and if so, how would I go about achieving this? I also want the ability to get user within the controller if logged in in order to do user based logic. On top of all this I also want a way to determine if the request is coming from my frontend or not within other middleware. How should I go about doing this while using as much built in functionality of Sanctum as possible?

Thanks in advance!

0 likes
1 reply
TS1997's avatar
Level 1

I looked into this further today and did manage to get the desired result using the following middleware. Is this a good solution or should I do something differently?

Please or to participate in this conversation.