I'm trying to build a RESTful api with restify.js, but I don't want to expose the api to everyone. And I'm going to use token-based authentication. The process in my mind is like this, I'm not sure whether it is reasonable.
the user send username/password to an api to acquire the token.
this token should be included in the request for the calls of every other api.
If this is reasonable, is there any node.js library I can use?
In addition, how do I protect the token? If someone intercept a http request with the token, then that person will get the api url and the token. Then he can send request as he wants. Is there a way to avoid this?
Thanks a lot!
Basic access authentication
Restify is bundled with an
authorizationParser
plugin.authorizationParser
parser out theAuthorization
. When the plugin is in use, it will makereq.username
andreq.authorization
properties available. Format of the latter is:Your server will need to selectively intercept the requests that require authentication and validate user access credentials.
Here is an example server that will require authentication for all calls:
The easiest way to test is using curl:
Restify comes with inbuilt JsonClient that supports basic authentication, e.g.
OAuth 2.0
If you prefer the token authentication, then you can use restify-oauth2 package that implements Client Credentials authentication flow, which is what you are after.
The documentation page describes step-by-step how to setup such authentication, including roles of each endpoint, and there is a code example in their repository.
Summary
Regardless of which method of authentication you choose, all of them require you to use HTTPS. The difference is that if username/password is compromised, user would need to change their credentials. If token is compromised, then user would need to request a new token. The latter can be done programmatically, while the former usually relies on hardcoded values.
Side note. In production, credentials must be considered "compromised" if transferred at least once over an insecure channel, e.g. compromised HTTPS, as in case of SSL bug, such as Heartbleed.