Search code examples
node.jshttpsecurityjwt

Block API access for any other resource except Frontend


I have a route api/v1/track and I want to send some data (JSON) by given track ID, but I want to send response for only my frontend requests or my mobile app, not any other request from anywhere!

I am using Node JS and Express, I implemented some JWT config for authentication of users with tokens but I do not know how to limit this access for this route without any pre created token

app.get("/track/:ID" , (req , res) => {

    // Block forbidden requests ... 

    // If request is from my specific resource ( Frontend or App ) then : 
    res.json(something)
}) 

I just do not want to let people use my API information, I also need that before user be authenticated for sending data to my Vue SPA.


Solution

  • There is no generic way to limit the use of your API only to your own web page. An API on the web is "on the web" and any programming tool on the web can reach it.

    As others have said you can implement CORs protection, but that only prevents people from accessing your API from their own Javascript in their own web pages - it does not prevent other scripts or programming tools (like curl) from accessing your API. CORs is a client-side protection that is only enforced within modern browsers. CORs does not apply to other ways your API could be accessed such as by script or other programming tools.

    The only real solution here is to implement authentication for all API requests and then to protect your server from abusive use of the API. The idea behind authentication is that you require some sort of authenticated login/account before the API will serve any result. For use in your own web page, you presumably have some sort of login that can be used for the authentication.

    Then, on the server, you need every API call to check for the presence of a login credential such as a verified login cookie, verified JWT token, etc...

    This prevents just open use of your API, but obviously people can still make an account on your site and then use those credentials to programmatically use your API. The only way to control that is to implement server-side protections such as rate limiting to prevent any abusive use of the API that might impact the quality or responsiveness of your server.

    For API servers at places like Google, they will typically require you to register for some sort of developer account and get some API access credential that you can then use with the API. As part of that, you have to agree to their terms of service and, if you violate those terms of service, they can revoke your API credential. They will also actively control your access with rate limiting and, in some cases, bandwidth usage too.