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

HardDrive's avatar

Secure laravel api route from being called outside of application

I have seen similar questions on here but couldn't find an answer. I have an api route that I want to utilise with a Vue component that sits on a public page. It looks up addresses from a post code. How can I make sure this route can only be used from the same web app and not called directly please. The page I want to put it on is public so there is no logged in user so I don't think I can use something like Sanctum in this scenario.

Many thanks in advance

0 likes
14 replies
Snapey's avatar

Just put the route in the web routes file and wrap it in Auth middleware. The browser will send the user's cookie with the XHR request and therefore the route can be restricted to authenticated users only.

1 like
HardDrive's avatar

Thanks @Snapey this is on a public page so there is no logged in user at this stage

HardDrive's avatar

That looks like a good solution I'll check it out and post back thanks

HardDrive's avatar

Ok I'm nearly there with this, the temporary signed url is great I could maybe pass this as a prop to my component but if I add a url parameter to the URL after it is signed it invalidates the signature 🤔

Snapey's avatar

@HardDrive the other way is to generate a token, store this in session and pass it to the client as a prop

accept the token as part of the request and see if it matches session

HardDrive's avatar

@Snapey could you elaborate on this please. How would I generate a session if not logged in. This would be useful to store partial progress too as I have a multi step form

Snapey's avatar

@HardDrive ill answer anyway, all users have session, whether logged in or not. For instance, csrf uses a token in session

HardDrive's avatar

@Snapey thanks, I need to brush up on this. SO CSRF token is unique per user browsing session? so if I wanted to log progress I could use this to save progress etc. Im guessing CSRF is based on cookie or whatever session driver is being used?

Snapey's avatar

@HardDrive no, don't use csrf as it will be regenerated for every form, use data stored in session

install laravel-debugbar it gives you insight into what is stored in session

HardDrive's avatar

Ignore my last response it was too vague a question.

HardDrive's avatar

A combination of a signed url and post request worked perfectly thank you 🙏

Please or to participate in this conversation.