What is the best secure way to get a JWT token from a node server from a javascript app without using a form?

梦想的初衷 提交于 2020-01-16 20:06:43

问题


In my case, I have a React app (using Next) that need to use an API provided by a node / express / mysql app.

My idea was to have an endpoint (/login) to provide a JWT Token based on user / password (that check the user in the database and create token based on the id of the user) and then use the JWT token to use the API endpoints (those token are stored in the mysql as well). But in order to do that, and because there is no form, I would have to store the credentials (user and password) in the client side app and therefore would be readable by anyone. Am I doing things right and if not, what are the other options to securely make the client side APP use the API endpoints ?

The React and the Node / Express are on the same domain and CORS is set by default by express from what I read. Also, HTTPS is activated.


回答1:


  1. generate web token
  2. do encrypt using becrypt npm
  3. store it in DB and cookie in the client side in encrypted form while the first-time user is login
  4. create on middleware which directly accesses your cookie and check-in your database and make your user login for a long time if your cookie token match with database token. like below example

  5. sample project : https://github.com/karenaprakash/books_review.git

  6. refer to this full application

  7. visit this project. I hope this will help you.




回答2:


Basically the JWTs allow you to avoid using sessions completely & to not store them in DB, a JWT is like a passport that you give to a user, that states his (ID, maybe username for example), role & any other data (that is insensitive if someone sees), so you should never store a password in a JWT

Security of the JWT basically lies in the fact of that no other entity can imitate it (if you use a strong key for signature) & although possible to encrypt your JWT, you don't have to encrypt it as long as you don't put sensitive data in it. I think you should try to have a look on this website to see how the signature protects the authenticity of the JWT

So you should make the /login API, this will check your user credentials & then give him the JWT (that states he is user 'joe' for example with the role 'admin') & then you check & verify this JWT in your filters to authenticate & authorise the user for the actions in your webapp

To get the JWT, a user must provide his credentials to you in a HTTPS connection, which will make the connection itself encrypted, thus protecting his credentials from eavesdropping or man-in-the-middle attacks



来源:https://stackoverflow.com/questions/58076644/what-is-the-best-secure-way-to-get-a-jwt-token-from-a-node-server-from-a-javascr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!