Search code examples
restapisecuritygomux

REST API only accessible through my React client


I'm building a React.js application that will interact with my REST API built in Go.

React will use Javascript Fetch API to send requests to my API.

The problem is I would like to secure my API from being requested from elsewhere. No one should directly be able to access my API either through the URL or through any other client like Postman.

I know what JWT is but this does not solve my problem because anyone can access the token through the browser and then continue to request the API outside the React client using the token.

I have researched extensively but nothing has really fit my description.

Thanks a lot for you help, in advance.


Solution

  • This is an inherently unsolvable problem. React runs on the client. The client controls the code that it executes. Hence, any mechanism you use to restrict the API usage to just your React client will be discoverable and reusable in other client contexts. You cannot control the client, and attempts to do so will be broken if the payoff is valuable enough.

    You can attempt to harden it somewhat by using short-term authorization tokens, but there is nothing preventing that token from being grabbed and reused in another context.

    If you have to restrict access to an API, you should have a public API which is less dangerous or privileged, and the public API should make use of your private API, effectively proxying the calls to hide the private API, as well as to ensure that only validated queries are executed against the more privileged API.

    If you could describe the problem you're trying to mitigate, though, there may be other solutions available.