Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authentication strategy for REST API and mobile app

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.

Thanks!

like image 875
user3470440 Avatar asked Apr 03 '14 13:04

user3470440


1 Answers

Now you can use Passport.js with JWT (JSON Web Tokens) with Passport-JWT. It's pretty easy to use.

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.

like image 102
Stefan Avatar answered Nov 14 '22 10:11

Stefan