2

I'm making my first node + express app and I'm using a npm module that makes calls to an external api.

I've a login page with a form where the user enters the credentials, which are then passed via post (ajax client-side, app.post server-side) and used to make the initial api call (using the npm module) which returns an auth token. All of the consequent api calls (using the npm module) are made using that token.

My question is: What is(/are) the best way(s) to handle that token ? Save it in a variable/object and export it, then require it on the js files where I need the token ? Use sessions (which would probably be a good idea to avoid asking the user to re-login) and store the token in that session ?

nip
  • 1,609
  • 10
  • 20

1 Answers1

1

I would suggest you to use jsonwebtoken module to generate token

Now how to use it

  1. When user tries to log in thensedn those username/email and password to server.
  2. Check user credentials if its valid then use jwt.sign method to generate token which contains the userId (or any some value to uniquely identify user).
  3. send that token in response to the login request.

  4. On receiving token on client side save it in some service.

    (Upon every API call -client side)

  5. when making subsequent calls to API add that token to the request (I would suggest to add it in Authorization header like this Authorization Bearer (token).

    (Upon every API call - server side)

  6. Now when server get the API request it will fetch token from request header and check validity of token using jwt.verify method and when request passes token verification stage you can then send requested data in response.

    Note: For adding token verification stage you can use express's middleware concept. To do this you can create an separate Auth module which exports a method called verify in which you can use jwt.verify and require that Auth module and put the Auth.verify method as middleware

Nishant Desai
  • 1,492
  • 3
  • 12
  • 19
  • I dont understand how its useful to use jwt here. I need to store a token than I get from an external api when I make the first call. – nip Dec 12 '16 at 17:27
  • You have two options storing your token in LocalStorage/SessionStorage (vulnerable to Cross-site scripting aka XSS attack )or saving it in cookie (vulnerable to Cross Site). I would recommends that you store your JWT in cookies for web applications, because of the additional security and flexibility they provide, and the simplicity of protecting against CSRF with modern web frameworks. HTML5 Web Storage is vulnerable to XSS, has a larger attack surface area, and can impact all application users on a successful attack. – Nishant Desai Dec 12 '16 at 18:55