Search code examples
node.jsrestjwtrestful-authentication

Securing Node.js RESTful APIs


I'm newbie in Node.js and just want to create RESTful API with it for my game in Unity3D. Just at the end of the game I want some information like name and phone number, etc from player if he/she wants to share. I know how to implement this server but my problem is with security. I've search a lot about security in Node.js but I've not figured it out yet. In my searches I've saw there is a npm package which is JWT and figured out how to use it. As I know we send a request to the server and in response it returns a bearer token which we can set our header with it and use GET, POST or other methods. My problem is that anyone can send a request to that URL and get that token and do other things (I think I made a mistake). So what is the solution for security of this type of server ?


Solution

  • Well there are multiple authentication strategies (basic, oauth, token, cookies). Since you have already chosen the JWT strategy I will try to explain it.

    1. User registers (email, password, phone, name, etc...)
    2. Your server returns a 201 and a JWT token signed specifc for that user jwt.sign({ id: user.id, role: user.role }, 'secret', { expiresIn: 60 * 60})
    3. Then you can add a middleware to your routes that validates if the token is in authentication header and if the token is valid. jwt.verify(token, 'your secret')
    4. Since you are using tokens in your headers you should use HTTPS to encrypt your http requests
    5. You also need a login endpoint that receive the id and password and generate a new token for that user because tokens can expire.

    Usually I use this package: https://github.com/auth0/node-jsonwebtoken where you can also set the encryption algorithm and more options.

    Another explanation containing images: https://stackoverflow.com/a/45978644/4120554