I’m creating a REST API server with Node.js and Express + MongoDB.
This API will have different mobile clients (iOS, Android) and possibly a web app later on.
I need users to login in order to perform some API requests. There are no 3rd party apps I want to connect with (no Facebook, Google etc). I also don’t want to force the users to visit a webpage or anything like that in order for them to login.
From what I’ve seen on my many searches on SO, the best approach would be to let users login with full credentials once, send them a token in return, and use that token to verify future requests until it expires.
However, I’m not sure how to implement this.
I’m very confused with all of the different strategies. Is this done with basic authentication over HTTPS, with OAuth, OAuth 2.0, … ? I just don’t know what to use.
Also, I really don’t want to reinvent the wheel here, not because I’m lazy, but mainly because of security concerns. Is there a library I could use to implement this? I’ve heard of Passport, but I couldn’t understand if this is doable or not. This sounds like such a generic thing I’m sure there’s a simple solution out there.
Once a user is logged in, you send a token to the user. The token contains data about the user, like an id (encoded, of course). On the subsequent requests (at least where authentication is required) you make sure, that the client sends the token. On the server, you can see who sent the request (and e.g. check the user’s authorization), just by looking at the token. For more info on how JWT work check this out.
There are different ways to send the token. Just have a look at the docs and it’ll be clear. If not, this also helped me.
There is an example of RESTful service with oauth2 authentication: https://github.com/vedi/restifizer-example. I hope it will help.
I feel you need to setup a Token Based Authentication process in your server, so you can make requests from different types of clients (Android, iOS, Web, etc.). Unfortunately, Passport documentation (and Passport-based tutorials) seems to be aimed for “web applications” only, so I do not think you should be using it for those purposes.
I did something similar following this great tutorial: http://code.tutsplus.com/tutorials/token-based-authentication-with-angularjs-nodejs–cms-22543
The client part in this tutorial is based on AngularJS, but can easily apply the same principles in a mobile client (it is just a matter of making HTTP requests including a token retrieved when you post in “/signin” or “/authenticate”).