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

KieronWiltshire's avatar

Laravel Passport - consuming API with javascript question

I currently have a backend API and a ReactJS front-end application with the entire API being authenticated using passport.

The issue I currently face is that my front-end application stores the bearer token in HTML5's localstorage. Now the issue with this is that it's prone to XSS attacks, therfore I would like to move it to a more stateful based approach, but only for 1st party consumers of the API. The reason is that the API is consumed by other 3rd party applications.

So with this in mind, I started looking at this section of the documentation: https://laravel.com/docs/master/passport#consuming-your-api-with-javascript

My API is on a sub-domain like api.example.com with my front-end being served from example.com. So I cannot embed the CSRF token directly into the HTML, so my first question is what would be the best practise to obtain the CSRF token? (I looked at Laravel Airlock which exposes a route and set's the CSRF token as a cookie which it then validates, can I do this already in Passport?)

The other issue I have is that the documentation tells me to use CreateFreshApiToken middleware as part of my web middleware group, but doesn't really detail exactly how this works. Do I need to use Auth::login($user) as usual, does this then automatically create the API token for me? I'm just unsure how to effectively use passport.

0 likes
2 replies
fylzero's avatar

@kieronwiltshire I don't believe CSRF acts like CORS and explicitly disallows cross site. It basically creates a token and validates against it when the form is submitted.

This is just my assumption, everyone can keep me honest here.

I also am not sure but I don't know if CORS blocks different subdomains. Either way CORS only protects against modern browsers and CSRF should ideally be implemented.

24 likes
KieronWiltshire's avatar

You misunderstand, I would like CSRF protection, I mentioned the sub-domain saying that simply embedding the CSRF token into my HTML isn't possible. I appreciate the reply nevertheless!

Please or to participate in this conversation.