How to restrict access to my Next.js APIs for my application - node.js

I am building a Next.js application in which I want to restrict access to my APIs. I only want my application to make those requests.
I once built an app with MERN stack, and I remember I used cors to only allow my domain to make requests to my APIs. But apparantly cors does not work with nextJS, and I tried many npm modules such as nextjs-cors but they didn't work.
I am thinking about using firebase App Check in order to check if this is my app that is making the requests, but I am still hesitant.
What do you think is the optimal and professional solution for this?
P.S.: Is there a similar behavior to cors in but in NextJS because I also remember cors did not allow postman to make requests as well to my APIs.

That is what API keys are for. Since you have control over both client and server, in client requests you can add a random key to headers when you make request. Then on the server, you can extract the headers console.log(req.headers), if the headers include the specific key and matching value, you process the request if not you reject the request.

Related

How can i hide API Key in an Electron JS Project?

i'm working on an electron js app & i need to connect it to an API
knowing that the source code of an electron-js app is visible it's a huge security risk to leave the API key there !
how can i solve this problem ?
Instead of having the electron app (whether from the page or from the main process) make a request to the API directly, you can have it make a request to your own server instead - then, your server can make the request to the API, so that the key is only visible to your server, and isn't exposed publicly anywhere.
This will also let you gate requests from clients - if, for example, the credentials a client sends don't match what you need, or if they make too many requests in too short a time, you can cut them off.
You can't. If API key is shared, it's probably designed to be used in the backend.
The solution for that is to create a backend API for proxying API calls. Such proxying API should utilize authentication, so each user must send individual credentials.
How about obfuscate it using a utility like js-beautify.

API Calls from HTTPClient or Backend?

I'm currently developing an Angular 6 page where we are doing some Http Post calls and sending the authentication as the header. The header is static (fixed password).
Is there any security differences sending it from the Angular frontend side with HttpClient, or sending it to an endpoint in our Node.Js backend (on cloud premises) and sending it there? Our thinking is that the "header" will be "hidden" for the client since we are sending it through our backend instead.
Another note, we will have the entire site behind authentication, and the clients logged obviously have the right to see the authentication, but we would like preferably not to.
Any thoughts and suggestions?
Depending on what you are trying to do with your post request, In previous projects I have worked on we have used your second approach and used a backend to validate requests before sending them on as I also have worked with secure systems and as a rule of thumb don't trust the client.
Here is some information from Angular's website on security with HttpClient https://angular.io/guide/http#security-xsrf-protection
I hope it helps.

How to make Node API only accessible by web app?

I'm developing a web app with React and an GraphQL API with Node.js / Express. I would like to make the API more secure so that its harder for API requests that don't come from the web app on the browser to get data. I know how to do it with registered users. But how to make the non-registered user still be able to access some basic data needed for the app?
Is it possible to put some kind of key in the web app - so the API call can't be replicated for others through sniffing the network dev tool in browser and replicating in Postman? Does SSL/TLS also secure requests in that browser tool? Or use like a "standard" user for non-registered visitors?
Its a serverside web app with next.js
I know theres no 100% secure api but maybe its possible to make it harder for unauthorized access.
Edit:
I'm not sure if this is a problem about CSRF because Its not about accessing user data or changing data through malicious websites etc. But its about other people trying to use the website data (all GET requests to API) and can easily build there own web app on top of my api. So no one can easily query my api through simple Postman requests.
The quick answer is no you can't.
If you trying to prevent what can be describe as legit users form accessing your api you can't really do it. they can always fake the same logic and hit your webpage first before abusing the api. if this is what your trying to prevent your best bet is to add rate limiting to the api to prevent a single user from making too many request to your api (I'm the author of ralphi and
express-rate-limit is very popular).
But if you are actually trying to prevent another site form leaching of you and serving content to their users it is actually easier to solve.
Most browsers send Referrer header with the request you can check this header and see that requests are actually coming from users on your own site (this technique is called Leech Protection).
Leaching site can try and proxy request to your api but since they all going to come from the same IP they will hit your rate limiting and he can only serve a few users before being blocked.
One thing the Leecher site can do is try to cache your api so he wont have to make so many requests. if this is a possible case you are back to square one and you might need to manually block his IP once you notice such abuse. I would also check if it's legal cause he might be breaking the law.
Another option similar to Referrer is to use samesite cookies. they will only sent if the request is coming directly from your site. they are probably more reliable than the Referrer but not all browsers actually respect them.

Single Page Web Apps, CORS and security concerns

The situation
I am writing a Single-Page-Web App (using Angular). Lets call it SPA
Another team-mate is writing some APIs (using Node.js). Lets call is Server
My SPA is to Login to the Server using login/passwd, and do some stuff
My team-mate has decided to use cookies to track the session. Hence, upon a successful login, a http-only cookie is to be set in the web-browser the SPA is loaded in.
The problem
If we put the SPA in the Server's public_html dir, all works well. This, however, makes the SPA as a part of the API code. This breaks our build process, since every version upgrade to the SPA now requires upgrading the API too.
If we host the SPA in a seperate webserver that only serves the static SPA files, I run into CORS issues. Since the SPA comes from a different origin than the APIs it is trying to access, the browser blocks the ajax calls. To overcome this, we will have to set Access-Control-Allow-Origin on the server side appropriately. I also understand that Access-Control-Allow-Credentials:true needs to be set, to instruct the browser to set/send the cookies.
Possible solutions
We create a build process which does a git-pull to the Server's public_html dir every time the SPA gets upgraded. I am trying to avoid this to keep the client and server upgrades separate.
We create a proxy kind of situation, where the Server doesnt store the SPA files, but collects them on-demand from another server that hosts the SPA files. In this case, the web-browser will see the SPA files and subsequent ajax calls from the same origin.
We code the server to set Access-Control-Allow-Origin:* in its responses. Firstly, this is too open and looks insecure. Is it really insecure, or is it just my perception? Also, since we are setting Access-Control-Allow-Credentials:true, Chrome complains Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true.. To overcome this, we will have to put exact origins (perhaps using a regex) in the Access-Control-Allow-Origin. This may seriously restrict us from distributing our SPA to users in unknown domains.
For a Server API designer, is Cookie based authentication the recommended way to handle Authentication for SPAs? OAuth2.0 and JWT based Authentication seems to suggest that Cookies based Authentication is not right for SPAs. Any pros/cons?
Kindly comment on the above options, or suggest any others that you may have used. Thanks in advance.
I think the issue is that your terminology is confusing. API is not an server, its an application that lives on a machine that can also be a server. If you make a NodeJS API, I suggest you use a Nginx server as a reverse proxy before it. Assuming you want the Nginx server, API and SPA files all on same machine, you can deploy your API to a directory and your SPA to another directory and have Nginx route the requests accordingly.
So I believe solution 2 is way to go. From there you can easily scale by increasing number of instances(if you use AWS) and load balance them or separate your API into its own application server.
As far as authentication. I have always preferred using Header Authorization with access tokens over cookies for SPA or API request. The idea that each request is self contained and does not require a persistent string kept on the browser is more appealing to me, though you can save access token via local storage.
I would go with either solution 2 or 3.
2: you could set both (webpage and API) on the same server (or use reverse proxies) so that from an outside perspective they share the same origins.
3: in the case of an API, the same origin policy becomes less important. The API is to be consumed by clients that are not part of your web application anyways, no?
I would not see any issue in setting a more lax allow origin header. And by more lax I don't mean wildcard, just add the origin of your webpage. Why do you want to wildcard it?

How does Firebase handle cross origin issues?

Looking through the Firebase FAQ I can't see how cross domain issues are handled. Obviously, we don't want to serve on the Firebase domain, is it CORS, hidden iFrame, other? Would we need to create a sub-domain that points at the IP of the sharing server?
Let me answer this question in two parts, as there are multiple ways to communicate with the Firebase Servers.
Firebase JavaScript Client - The Firebase Javascript Client maintains a real-time bidirectional connection to the server. Under the covers, this uses WebSockets whenever possible (which have no limitations with regard to cross-origin connections) and falls back to hidden-iframe-based jsonp long-polling on older browsers (which sidesteps cross-origin issues by only doing requests).
Firebase REST API - You can also get / set data from Firebase using the REST API, which uses CORS to allow cross-origin requests.
So in summary, it should "just work" and you don't need to do anything special.

Resources