Secure rest api node js - node.js

I would like to expose a problem to which I just cannot find a solution, although I have been informed several times on the web, the resources I find do not satisfy my curiosity.
The question is the following:
Suppose we have a rest API in node js (express) on the following endpoint -> / stars.
Suppose we want to sell this API with the endpoint/stars to a certain target of customers, the endpoint will therefore only allow customers who buy the API to use it.
The problem arises spontaneously, let's suppose that the pizza company buys my API and that I generate an access token for them, then they would call my endpoint with their token to have the resource, so far very good.
However, all the requests are easily visible.
Example Chrome> dev tools> network and I see not only the endpoint with the full address, but even the payload that is passed!
So as an attacker I could very well (without paying the API) catch the pizza industry using the endpoint/stars with a token, copy everything and slap it on my services by providing the same token and the same endpoint.
I already know the existence of tokens like jwt but they don't solve the problem anyway, as that different token only has the expiration.
Even if it expires after 15 minutes or after 3 minutes, just retrieve another one and provide an identical request with the same token, would anyone be able to direct me to a solution?
The only one I've seen to find a solution to this is Instagram that sends behind a payload of thousands of lines, is it really the only method?
note: it is not even public.

#xVoid
The first thing you can set an encryption/decryption module for your response data with the help of the crypto module in node.js, Here you send encrypted response and the your API client decrypt your response and use it.
You can set a key for your API it means every time your client or user send you a request they have to send that key in the body, not header so other people can't
get your data because they don't have that key, and in express you can set middleware to validate this key is exist or not if not simply return "You are not authorized"
If you aren't getting any point or you want to go deep on particular thing just let me know

You may simply use http-only cookie and send the token in cookie, instead of normal header

A customer using your endpoint should not be sharing their API keys with the end-users.
This means that any customer using your service should create at least a proxy server to your specific endpoint.
CLIENT GET /pizza FROM CUSTOMER -> CUSTOMER GET /pizza?apiToken=<...> FROM SERVICE
Obviously there can be a man in the middle attack between the CUSTOMER and your SERVICE but that's is unlikely to occur using SSL (Related: Are querystring parameters secure in HTTPS (HTTP + SSL)? )
If a CUSTOMER suspects that their api key was leaked they should revoke it and request a new one to your SERVICE.

Related

Preventing fraudulent use of GCP access tokens appearing in requests issued by the frontend

The frontend of my web app uses an access token (periodically generated by the backend) to issue requests to GCP text-to-speech. Issuing requests from the frontend rather than from the backend is essential to keep down both the costs of my service and the delays experienced by the user.
A not-well-intending user might use my app to synthesize speech for a short text, open the Network tab of the browser tools, and get the access token from the request headers sent by my frontend to GCP. He could thereafter use this access token to synthesize speech for a large corpus of text, with no way for me to catch him. How can I change the way I use access tokens to prevent this kind of fraudulent use?
Here are some directions I have thought about, but am not sure what is supported by GCP or whether there is an even better approach:
Create a separate API key for each user of my app and generate access token for the specific user. Then, even if a user uses his token outside of my app, GCP would have a record of the requests made by that user and I could request that record using the API to charge him.
Make access tokens single-use. This way, even if the user obtains the access token as it is being sent as part of a request, he will not be able to use it for another request.
As John Hanley mention you would rather change your design so the backend makes requests to Text-to-Speech on behalf of authorized clients

Authenticating WebSocket Connections

This may seem like a pretty noobish question, but I just recently got into Node.js and am needed to make sure that the same kind of Authentication that occurs in my Laravel App happens in Node.js.
Clearly, I need to use an API, but I am confused about how to do it in a manner that is secure. I have looked into this article:
https://www.ida.liu.se/~TDP024/labs/hmacarticle.pdf
And have looked through their algorithm into building an API. But I do not understand how it would be secure.
According to the post, you store a public and private key in a Database. The public key can be seen by everyone but the private key is, well, private. However, when sending it to the server, you send a hashed version along with other data, of the private to the server.
This sounds all well and fine. However, does that not mean that the public key and the hash is public, thus the private key is exposed as well?
For example lets say I try to establish the following connection
ws://example.com/pull?public=A89-3NJ2-KAN-NKSN1&hash=QmFzZTY0IHRoZSBoZWxsIG91dCBvZiBtZSBiYWJ5Li4uLi4u
What stops another user from just sharing this link giving an unrelated user access to it?
The article you linked to describes how to authenticate one single request, not an entire session. That is, the user sends the public api_key along with some request data that describes the specific request for the API (like, { "action":"latest_price", "symbol":"GOOG"} for a stock market API).
To authenticate, the user also uses a shared API-access secret key as an HMAC key to compute HMAC(secret, api_key+request). No one else can compute this if they don't know the secret. Only the user and the server should know secret, because it's basically the user's password to use the API.
The situation you describe is very different: you're using a WebSocket, so I assume you'll be sending requests interactively. If you want to authenticate the entire socket session, this approach doesn't make sense, since it's designed to authenticate a single request. You can apply this approach to individual requests inside the WebSocket connection.
For authenticating a new connection (i.e., "what logged-in user is opening this connection?") using auth cookies is appropriate, just as you would for a traditional HTTP connection.
Below, I'll assume that the purpose of the Web Socket is to send only one request (which really makes me wonder why it's a WebSocket), so that the request-level authentication makes sense.
What stops another user from just sharing this link giving an unrelated user access to it?
Nothing. Do you want someone else to submit a specifc request, while impersonating you? Then by all means, give them that link and tell them to use it.
The credentials in the link include an HMAC of the API request (plus your identity) that only you can generate, as the sole owner on your API secret key. If you give that HMAC to someone else, they can submit it and impersonate you for that specific request. However, they cannot create more requests, because they don't have your API secret to make more HMAC values for different requests.
In fact, if you didn't want that request to be submitted, you should not have used your secret to create the authenticating HMAC in the first place! Why did your authenticate a request that you didn't intend to be submitted?
Have a look at this
Essentially
make a "websocket preauth" request to the backend from the browser using the site's normal auth
backend returns a CSRF token in the response body and sets a "websocket auth" cookie with SameSite=Strict in the response headers
attempt to establish a websocket connection with the backend, with the addition of the CSRF token in a query parameter
the backend checks
that the websocket auth cookie and CSRF token are valid
that the value of the Origin header matches an approved domain
the backend sends a response and upgrades the connection to use websockets

How to handle Rest API user authentication securely?

For the last few months i've been working on a Rest API for a web app for the company I work for. The endpoints supply data such as transaction history, user data, and data for support tickets. However, I keep running into one issue that always seems to set me back to some extent.
The issue I seem to keep running into is how do I handle user authentication for the Rest API securely? All data is going to be sent over a SSL connection, but there's a part of me that's paranoid about potential security problems that could arise. As it currently stands when a client attempts to login the client must provide a username or email address, and a password to a login endpoint (E.G "/api/login"). Along with with this information, a browser fingerprint must be supplied through header of the request that's sending the login credentials. The API then validates whether or not the specified user exists, checks whether or not the password supplied is correct, and stores the fingerprint in a database model. To access any other endpoints in the API a valid token from logging in, and a valid browser fingerprint are required.
I've been using browser fingerprints as a means to prevent token-hijacking, and as a way make sure that the same device used to login is being used to make the requests. However, I have noticed a scenario where this practice backfires on me. The client-side library i'm using to generate browser fingerprints isn't always accurate. Sometimes the library spits out a different fingerprint entirely. Which causes some client requests to fail as the different fingerprint isn't recognized by the API as being valid. I would like to keep track of what devices are used to make requests to the API. Is there a more consistent way of doing so, while still protecting tokens from being hijacked?
When thinking of the previous question, there is another one that also comes to mind. How do I store auth tokens on client-side securely, or in a way that makes it difficult for someone to obtain the tokens through malicious means such as a xss-attack? I understand setting a strict Content-Security Policy on browser based clients can be effective in defending against xss-attacks. However, I still get paranoid about storing tokens as cookies or in local storage.
I understand oauth2 is usually a good solution to user authentication, and I have considered using it before to deal with this problem. Although, i'm writing the API using Flask, and i'm also using JSON Web tokens. As it currently stands, Flask's implementation of oauth2 has no way to use JWTs as access tokens when using oauth for authentication.
This is my first large-scale project where I have had to deal with this issue and i am not sure what to do. Any help, advice, or critiques are appreciated. I'm in need of the help right now.
Put an API Gateway in front of your API , your API Gateway is publicly ( i.e in the DMZ ) exposed while the actual API are internal.
You can look into Kong..

How to authenticate requests using ServiceStack, own user repository, and device ids?

I'm building a mobile app and a ServiceStack web service back-end. The Authentication stuff in ServiceStack looks great but easy to get lost in its flexibility - guidance much appreciated. I'll be using my own db tables for storing users etc within the web service. I'd like to have a registration process and subsequent authentication something like this:
the user initially provides just an email address, my web service then emails a registration key to the user
the user enters the key. The app sends to the web service for registration: email, key & a unique device identifier.
the web service verifies the key and stores the email & device id. It responds back with an auth token that the app will use for later authentication.
Then subsequent web service requests would provide the device id and auth token (or a hash created with it). The app is not very chatty so I'm tempted to send the authentication details on each web request.
Question 1: Should I hook into ServiceStack's registration API or just add a couple of custom web service calls? e.g. without using ServiceStack's registration I would:
post to a registration web service with the email address and device id. My web service would send the registration email with a key and add a record to the user db table.
when the user enters the key it would again post to the registration web service, this time also with the key. My web service would validate the key and update the user table marking the user as registered, creating and recording the auth token & returning it to the caller
subsequent requests would be sent using http basic auth with the device id as username and the auth token as password. The service is not very chatty so creds will be sent with each request.
I'll implement a CredentialsAuthProvider that'll get the creds with httpRequest.GetBasicAuthUserAndPassword() and validate them against the db data.
But it feels like I should use registration built in to ServiceStack.
Question 2: What's wrong with passing the authentication details with each request? This would make it easier for composing my app requests but it doesn't seem 'done' based on the ServiceStack examples. Presumably that's because it's inefficient if you have lots of requests to need to re-authenticate every call - any other reasons? My app will only make a single web request at most every few minutes so it seems simpler to avoid having sessions and just re-auth each request.
Question 3: Am I on the right track subclassing CredentialsAuthProvider?
Question 4: Is there any point using the auth token to generate a hash instead of sending the auth token each time? All communication will be over https.
Answer1: It will be OK. if you give multiple call as per requirement. Normally authentication works based on cookie, now you can store it on client and/or on server and match the user with it. Again here if you are using device you, can always use device instead of user to map and authenticate user. Based on your requirement.
I will prefer to use provider as it hides many details which you need to do manually instead. You are on right track. There are many blogs specifically for authentication and how to create custom authentication with service stack. If you like let me know I have book marked some will give it you. Best way to search latest one is checkout twitter account of Servicestack.
Answer2: This is again, I say as per requirement. Now if your user will be in WIFI zone only. (Mostly true for business users), then there is not limit for calls. Just give a API call and do the authentication in background. Simple JSON token will not hurt, It is few bytes only. But again if you have big user base who is not using good internet connection then it will be better to store authentication detail on device and check against that. Just to save a network call. In any case network call is resource heavy.
Answer3: Yes you are on a right track. Still check out blog entries for more details. I don't remember the code snippet and how it works with last update so I am not putting up code here.
Answer4: This is answer is little complicated. Passing data over https and saving user from Identity fraud is little different thing. Now, if you are not generating auth token (hash based value) then you can pass user also over the http or https. Now, this can be used by another user to mock first user and send data. Even data is being passed through https but still data is getting mocked. Hashed based value is used to avoid this situation. And also there are couple of other business use cases can be covered using auth token.
Please let me know if I have understand you questions correctly and answered them?? or If any further details is required??

How do I secure REST API calls?

I'm developing the restful web app that using some popular web framework on the backend, say (rails, sinatra, flask, express.js). Ideally, I want to develop client side with Backbone.js. How do I let only my javascript client side interact with those API calls? I don't want those API calls to be public and be called by curl or simply by entering the link on browser.
As a first principle, if your API is consumed by your JS client, you have to assume, that it is public: A simple JS debugger puts an attacker into a position, where he can send a byte-for-byte identical request from a tool of his choice.
That said, if I read your question correctly, this is not, what you want to avoid: What you really don't want to happen is, that your API is consumed (on a regular basis) without your JS client being involved. Here are some ideas on how to if not enforce, then at least encourage using your client:
I am sure, your API has some sort of authentication field (e.g. Hash computed on the client). If not, take a look at This SO question. Make sure you use a salt (or even API key) that is given to your JS client on a session basis (a.o.t. hardcoded). This way, an unauthorized consumer of your API is forced into much more work.
On loading the JS client, remember some HTTP headers (user agent comes to mind) and the IP address and ask for reauthentication if they change, employing blacklists for the usual suspects. This forces an attacker to do his homework more thoroughly again.
On the server side, remember the last few API calls, and before allowing another one, check if business logic allows for the new one right now: This denies an attacker the ability to concentrate many of his sessions into one session with your server: In combination with the other measures, this will make an abuser easy detectable.
I might not have said that with the necessary clarity: I consider it impossible to make it completely impossible for an abuser to consume your service, but you can make it so hard, it might not be worth the hassle.
You should implement some sort of authentication system. One good way to handle this is to define some expected header variables. For example, you can have an auth/login API call that returns a session token. Subsequent calls to your API will expect a session token to be set in an HTTP header variable with a specific name like 'your-api-token'.
Alternatively many systems create access tokens or keys that are expected (like youtube, facebook or twitter) using some sort of api account system. In those cases, your client would have to store these in some manner in the client.
Then it's simply a matter of adding a check for the session into your REST framework and throwing an exception. If at all possible the status code (to be restful) would be a 401 error.
There's an open standard now called "JSON Web Token",
see https://jwt.io/ & https://en.wikipedia.org/wiki/JSON_Web_Token
JSON Web Token (JWT) is a JSON-based open standard (RFC 7519) for
creating tokens that assert some number of claims. For example, a
server could generate a token that has the claim "logged in as admin"
and provide that to a client. The client could then use that token to
prove that they are logged in as admin. The tokens are signed by the
server's key, so the server is able to verify that the token is
legitimate. The tokens are designed to be compact, URL-safe and usable
especially in web browser single sign-on (SSO) context. JWT claims can
be typically used to pass identity of authenticated users between an
identity provider and a service provider, or any other type of claims
as required by business processes.[1][2] The tokens can also be
authenticated and encrypted.[3][4]
Set a SESSION var on the server when the client first loads your index.html (or backbone.js etc.)
Check this var on the server-side on every API call.
P.S. this is not a "security" solution!!! This is just to ease the load on your server so people don't abuse it or "hotlink" your API from other websites and apps.
Excuse me #MarkAmery and Eugene, but that is incorrect.
Your js+html (client) app running in the browser CAN be set up to exclude unauthorized direct calls to the API as follows:
First step: Set up the API to require authentication. The client must first authenticate itself via the server (or some other security server) for example asking the human user to provide the correct password.
Before authentication the calls to the API are not accepted.
During authentication a "token" is returned.
After authentication only API calls with the authentication "token" will be accepted.
Of course at this stage only authorized users who have the password can access the API, although if they are programmers debugging the app, they can access it directly for testing purposes.
Second step: Now set up an extra security API, that is to be called within a short limit of time after the client js+html app was initially requested from the server. This "callback" will tell the server that the client was downloaded successfully. Restrict your REST API calls to work only if the client was requested recently and successfully.
Now in order to use your API they must first download the client and actually run it in a browser. Only after successfully receiving the callback, and then user entry within a short frame of time, will the API accept calls.
So you do not have to worry that this may be an unauthorized user without credentials.
(The title of the question, 'How do I secure REST API calls', and from most of what you say, that is your major concern, and not the literal question of HOW your API is called, but rather BY WHOM, correct?)
Here's what I do:
Secure the API with an HTTP Header with calls such as X-APITOKEN:
Use session variables in PHP. Have a login system in place and save the user token in session variables.
Call JS code with Ajax to PHP and use the session variable with curl to call the API. That way, if the session variable is not set, it won't call and the PHP code contains the Access Token to the API.

Resources