Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

panthro's avatar

Middleware for an API?

With my SPA's API, the auth:sanctum middleware ensures that a user is logged in before access it.

But I have various routes that don't require authentication, e.g. get all posts from all users, but ideally I would only like my frontend app to access the API, and not an app built by a third party.

Is there a way to protect the API in this way?

0 likes
3 replies
martinbean's avatar

@panthro No. If you don’t have authentication then the route isn’t protected.

You can use CORS, but this will only stop someone from being able to request the API in JavaScript on another domain. They’ll still be able to make requests server-side, or with cURL, or with a client such as Postman…

panthro's avatar

@martinbean thanks for the information, how can I enable CORS middleware - I know it's not foolproof as you have suggested, but at least it offers some minor protection.

Please or to participate in this conversation.