How to secure my REST-API? - node.js

I have an api build with node.js & express.js. For now I have a unsecured api where anyone can GET,POST,PUT,DELETE records.
I am facing following problem. My rest api should not authenticate users but applications. E.g. my mobile application should have a valid token to access the api. Same for web application.
Another user case: my api will be used by another application that only uses one single rest call. So somewhere in the code I don't know in an application I don't know (for most part) a rest call on my api will be triggered. How can I secure such access, since no cookies or sessions are involved?
My first thought was, create a user and a password. Each api call (via https) must contain the credentials. Password may be hashed. However I read this
Usernames and passwords, session tokens and API keys should not appear
in the URL, as this can be captured in web server logs and makes them
intrinsically valuable.
from https://www.owasp.org/index.php/REST_Security_Cheat_Sheet
Any suggestions on this? I read about oauth but this involves redirections and I cannot imagine how this would work with a mobile app e.g. on android.

You can use RSA encryption for this, have a look at ursa module for node.
A simplified process of using this is... Arrange you client applications to encrypt a secret password with a public key and on the server side decrypt it with a private one, check if the secret is what you expect and act accordingly...
There are plenty of articles about using rsa in applications, I am sure you will be able to pick up a more definite explanation of how to work it if you just google.
EDIT
I have just bumped into this post which has a more detailed write-up on this question.

There is a question of how applications get to know a username/password in the first place, but if you are OK with the general idea (which is safe, as long as you consider the environment in which the application runs to be safe), then you don't need to worry about username/passwords in URLs: simply use https instead of https.
https is encrypted so that only the 2 endpoints (the client and your API) can read even the URL. Any router/proxy/server in between sees only encrypted data and has no means of accessing your username/passwords.
Instead of a username/password, btw, just use an "Access Token", which is a long (read: hard to guess) string, and assign one access token per application. In your end, you keep the list of valid tokens in a DB, and authenticate against that. You can even attach expiry dates to those strings, if you wish so.
Adding access token as part of an https:// url is common practice.

Related

How to securely pass the API Key in the HTTP Header?

I am building a API suite to connect to our application. Each user will have an unique API key which will be passed in the Header.
I am here to ask, what is the best way to authenticate the user? I donot want the user to pass the API key without any encryption ?
I am passing the API key like this :
$headers['x-axpr-auth'] = '<API-KEY>';
Since, I am building the API myself, I have the flexibility to use different encryption/authentication techniques.
Using HTTPS is pretty much mandatory in this case so I'm going to assume you (will) do that.
If you have an API key with long-term validity, then you should consider using some kind of "temporary token" with (very?) limited validity - so the attack window is much smaller.
This is similar to using Basic Authentication (sending password with every request) versus sending credentials only once and using session cookie afterward.
You should look at existing authentication/authorization schemes - OAuth2 (with access and refresh tokens) may be relevant since you're building APIs. OpenID Connect builds on top of OAuth2 and provides a proper authentication layer.
Apart from that, it's uncommon to explicitly encrypt API token in an HTTP header, since the whole communication is already encrypted using HTTPS.

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..

client secret in OAuth 2.0

To use google drive api, I have to play with the authentication using OAuth2.0. And I got a few question about this.
Client id and client secret are used to identify what my app is. But they must be hardcoded if it is a client application. So, everyone can decompile my app and extract them from source code. Does it mean that a bad app can pretend to be a good app by using the good app's client id and secret? So user would be showing a screen that asking for granting permission to a good app even though it is actually asked by a bad app? If yes, what should I do? Or actually I should not worry about this?
In mobile application, we can embedded a webview to our app. And it is easy to extract the password field in the webview because the app that asking for permission is actually a "browser". So, OAuth in mobile application does not have the benefit that client application has not access to the user credential of service provider?
I had the same question as the question 1 here, and did some research myself recently, and my conclusion is that it is ok to not keep "client secret" a secret.
The type of clients that do not keep confidentiality of client secret is called "public client" in the OAuth2 spec.
The possibility of someone malicious being able to get authorization code, and then access token, is prevented by the following facts.
1. Client need to get authorization code directly from the user, not from the service
Even if user indicates the service that he/she trusts the client, the client cannot get authorization code from the service just by showing client id and client secret.
Instead, the client has to get the authorization code directly from the user. (This is usually done by URL redirection, which I will talk about later.)
So, for the malicious client, it is not enough to know client id/secret trusted by the user. It has to somehow involve or spoof user to give it the authorization code,
which should be harder than just knowing client id/secret.
2. Redirect URL is registered with client id/secret
Let’s assume that the malicious client somehow managed to involve the user and make her/him click "Authorize this app" button on the service page.
This will trigger the URL redirect response from the service to user’s browser with the authorization code with it.
Then the authorization code will be sent from user’s browser to the redirect URL, and the client is supposed to be listening at the redirect URL to receive the authorization code.
(The redirect URL can be localhost too, and I figured that this is a typical way that a “public client” receives authorization code.)
Since this redirect URL is registered at the service with the client id/secret, the malicious client does not have a way to control where the authorization code is given to.
This means the malicious client with your client id/secret has another obstacle to obtain the user’s authorization code.
I started writing a comment to your question but then found out there is too much to say so here are my views on the subject in the answer.
Yes there is a real possibility for this and there were some exploits based on this. Suggestion is not to keep the app secret in your app, there is even part in the spec that distributed apps should not use this token. Now you might ask, but XYZ requires it in order to work. In that case they are not implementing the spec properly and you should A not use that service (not likely) or B try to secure token using some obfuscating methods to make it harder to find or use your server as a proxy.
For example there were some bugs in Facebook library for Android where it was leaking tokens to Logs, you can find out more about it here
http://attack-secure.com/all-your-facebook-access-tokens-are-belong-to-us
and here https://www.youtube.com/watch?v=twyL7Uxe6sk.
All in all be extra cautious of your usage of third party libraries (common sense actually but if token hijacking is your big concern add another extra to cautious).
I have been ranting about the point 2 for quite some time. I have even done some workarounds in my apps in order to modify the consent pages (for example changing zoom and design to fit the app) but there was nothing stopping me from reading values from fields inside the web view with username and password. Therefore I totally agree with your second point and find it a big "bug" in OAuth spec. Point being "App doesn't get access to users credentials" in the spec is just a dream and gives users false sense of security… Also I guess people are usually suspicions when app asks them for their Facebook, Twitter, Dropbox or other credentials. I doubt many ordinary people read OAuth spec and say "Now I am safe" but instead use common sense and generally not use apps they don't trust.
Answering to 2nd question: Google APIs for security reason mandate that authentication/sign-in cannot be done within App itself (like webviews are not allowed) and needs to be done outside app using Browser for better security which is further explained below:
https://developers.googleblog.com/2016/08/modernizing-oauth-interactions-in-native-apps.html

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.

What's the purpose of the client secret in OAuth2?

I have an app that offers an API. This app is an OAuth2 provider.
I want to access this API (read & write) with a client-side only app. I'm using JSO to make this easier.
It works great.
The thing is, I don't have to enter my client secret (of the application I registered in my app) anywhere. And I understand why, it would then be available to anyone.
So, if I can access my api without the client secret, could you explain to me what is its purpose?
This discussion provides an excellent explanation of why the client secret is much more important for server-side apps than client-side apps. An excerpt:
Web apps [server-side apps] use client secrets because they represent huge attack vectors. Let us say that someone poisons a DNS entry and sets up a rogue app "lookalike", the juxtapose might not be noticed for months, with this intermediary sucking up tons of data. Client secrets are supposed to mitigate this attack vector. For single user clients, compromise has to come one device at a time, which is horribly inefficient in comparison.
Client Secret was used in OAuth 1.0 to sign the request, so it was required. Some OAuth2 servers (such as Google Web Server API) required the client secret to be sent to receive the access token (either from request token or refresh token).
OAuth 2.0 has reduced the role of the client secret significantly, but it is still passed along for the servers that use it.
This was also driving me insane until I saw an example that made the answer blindingly obvious.
I have to be logged into The Server before The Server will return a token granting access to My stuff.
In other words, The Server will present Me, the human, with a login screen if I don't already have a valid login session with The Server. This is why explanations always say something like "it's up to to the server to authenticate".
Sure, The Server does not have to require that I am logged in. Is this realistic? Will Dropbox really grant access to My files to anyone without a login? Of course not. Most of the explanations I've read gloss over this point as if it doesn't matter, when it's practically the only thing that does matter.

Resources