2

I have a Laravel 10 project that has both the front end and the back end within the same project.

This website renders information from a database. Everything works as expected.

I have two route files web.php and api.php

I have the following API route: https://example.com/api/product/1

This is an example of the output from that route:

{"id":1,"name":"name","description":"hello world"} 

I have other routes that return much more complex data.

I need access to the API routes from inside my application. I have some internal react components that use axios to retrieve the data. This part works fine.

What I am trying to do is to "secure" the API route so that it cannot be accessed from outside my Laravel application. Therefore, if the request is coming from my blade views or my react app then the server will return the data. However, if someone types the API address on the browser I want it to throw an error (not authorized).

Update: I am using Laravel Sanctum for auth, however, I am not looking to make API requests accessible to users with an authorized token.

I want the data to be controlled by the view, I don't want users to easily access the API, copy the data and take everything away with one click.

What is the best approach to designing such a system like this?

rfadeout
  • 21
  • 2
  • Google "Cross Site Request Forgery". I'm sure Laravel has something built-in that you can use to implement CSRF protection. Do note that if your application has no authentication at all (as in some sort of login), then there is nothing that stops anyone from mimicking what your frontend does. CSRF protection will slow someone down, but never stop them. – Peter Jun 26 '23 at 13:56
  • 2
    have you tried to use Laravel Sanctum in your project? – Romylussone Jun 26 '23 at 14:15
  • In order for your front-end application to send a request to your backend your code is downloaded by a client's browser and executed. It is the client that sends requests to your backend so it is the client that you need to authorise and not your application. – apokryfos Jun 26 '23 at 15:07
  • have you considered implementing apikey? so that your API won't be accessible without it? – Yusuf Giovanno Jun 26 '23 at 15:39
  • Currently using Sanctum. Updated question. I am not looking to allow access to certain users, I would like an API route to be accessible only to my react components or blade view. Upon further research, it seems that what I am trying to accomplish is impossible. I will probably need to pass the data directly to the blade view if I really want to hide the "raw" data object returned from an API. – rfadeout Jun 29 '23 at 15:56

0 Answers0