In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what is using NodeJS to achieve JWT principle". In daily operation, I believe that many people have doubts about using NodeJS to achieve JWT principle. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the question of "what is the principle of using NodeJS to achieve JWT?" Next, please follow the editor to study!
One. Why session management is needed
When we use nodejs to provide resful interface for front-end or other services, http protocol is a stateless protocol. Sometimes we need to obtain whether the user has permission according to the top and bottom of the request and operate according to the user's context. Therefore, the emergence of cookies session and jwt is a supplement to the HTTP protocol. It enables us to use HTTP protocol and state management to build a user-oriented WEB application.
II. Session and cookie
Session and cookies are related. Session is the session_id of the server under the client cookies, and the server stores all the status information of the current user corresponding to the session_id. Every time the client requests the server to bring the session_id in the cookies, the server determines whether there is specific user information, and if not, adjusts the login.
Cookies security is not good, attackers can obtain local cookies to cheat or use cookies to carry out CSRF attacks.
Cookies may have cross-domain problems under multiple domain names.
The information of session is stored on the server. When node.js deploys multiple machines in stke, we need to solve the problem of shared session, which leads to the problem of session persistence. Therefore, session does not support distributed architecture and scale-out, and can only save session data through database to achieve sharing. If the persistence layer fails, authentication failure will occur.
III. Definition of JWT
Jwt is the full name of json web token. It solves the problem above session. The advantage is that the server does not save any session data, that is, the server becomes stateless, making it easier to expand. Under what circumstances, it is more appropriate to use jwt. I think it is the authorization scenario because jwt is easy to use, low overhead and stateless at the back end, so it is widely used.
IV. The principle of JWT
The principle of JWT is that after the server is authenticated, a JSON object is generated and sent back to the user, as shown below.
{"name": "Zhang San", "role": "Administrator", "expiration time": "00:00 on July 1st, 2018"}
In the future, when the user communicates with the server, the JSON object will be sent back. The server relies entirely on this object to identify the user. In order to prevent the user from tampering with the data, the server will add a signature when generating this object.
5. Authentication process of JWT
Process description of JWT:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
The browser initiates a request to log in with a user name and password
The server verifies the identity to the database according to the user name and clear code, and packages the user identifier to generate token according to the algorithm.
The server returns JWT information to the browser. JWT should not contain sensitive information, which is very important.
The browser initiates a request to obtain the user's information, and sends the token you just got to the server, which is usually placed in header. The field is authorization.
The server finds that there is token,decode token information in the data, and then signs it again to verify the identity.
The server returns the user information of the user
The server can set the expiration time in payload, and if it expires, it can ask the client to re-initiate authentication.
6. The data structure of JWT
JWT includes the use of. Three parts of the style, including header (header), Payload (load) and Signature (signature)
Header header
{"alg": "HS256", "typ": "JWT"} / / algorithm = > HMAC SHA256// type = > JWT
This is a fixed way of writing, and the alg surface uses the HS256 algorithm.
Payload load, load
JWT specifies seven official fields
Iss (issuer): issuer exp (expiration time): expiration time sub (subject): subject aud (audience): audience nbf (Not Before): effective time iat (Issued At): issue time jti (JWT ID): number
In addition to these seven, it can be customized, such as expiration time
Signature signature
Sign the first two parts header and payload to prevent data tampering
HMACSHA256 (base64UrlEncode (header) + "." + base64UrlEncode (payload), secret)
Secret is a string that is saved at the backend. It is important to note that JWT, as a token token, may be put in URL in some cases (such as api.example.com/?token=xxx). Base64 has three characters +, / and =, which have a special meaning in URL, so they have to be replaced: = is omitted, + is replaced with -, / is replaced with _. This is the Base64URL algorithm.
7. How to use jwt
Bearer is also specified in the header information Authorization field of the HTTP request.
Authorization: Bearer
Transport over url (not recommended)
Http://www.xxx.com/pwa?token=xxxxx
If it is a post request, it can also be placed in the request body.
Eight. Used in koa projects
You can use off-the-shelf libraries, jwt-simple or jsonwebtoken
Let Koa = require ('koa'); let Router = require (' koa-router'); let bodyparser = require ('koa-bodyparser'); let jwt = require (' jwt-simple'); let router = new Router () let app = new Koa (); app.use (bodyparser ()); / / you can customize let secret = 'zhenglei'; / / verify whether you log in to router.post (' / login',async (ctx) = > {let {username,password} = ctx.request.body) If (username = = 'admin' & & password = =' admin') {/ / usually looks up the database. Here's a simple demonstration: let token = jwt.encode (username, secret); ctx.body = {code:200, username, token,}) / / verify whether you have permission router.get ('/ validate',async (ctx) = > {let Authorization = ctx.get ('authorization') let [, token] = Authorization.split (''); if (token) {try {let r = jwt.decode (token,secret)) Ctx.body = {code:200, username:r, token}} catch (e) {ctx.body = {code:401 Data:' did not log in'} else {ctx.body = {code:401, data:' did not log in'}) App.use (router.routes ()); app.listen (4000)
Implement two interfaces, one is / login to verify whether to log in, and the other is validate to verify whether you have permissions.
When requesting the login interface, the client takes username and password. The backend generally checks the database to verify whether the current user exists. If so, sign the username. Do not bring the signature to the sensitive information such as password.
The client receives the token token from the backend, and then requests other APIs, such as / validate in this example. When ajax requests, you can specify the authorization field in header, get the token at the backend for decode, and then sign the header and payload again. If the signatures are the same, indicating that they have not been tampered with, permission verification is passed. Because it is a synchronous process, you can use try catch to catch errors
Nine. Realization of the principle
Sha256 hash algorithm, you can use nodejs's built-in encryption module crypto to generate base64 strings. It should be noted that the generation of base64 needs to be replaced by +-=, = omitted, + replaced by -, / with _. This is the Base64URL algorithm.
Token tokens are made up of header, payload and sigin passing. To make up
The decoding of base64urlUnescape is fixed, and decode gives the content of base64.
Let myJwt = {sign (content,secret) {let r = crypto.createHmac ('sha256',secret) .update (content) .digest (' base64'); return this.base64urlEscape (r)}, base64urlEscape (str) {return str.replace (/\ + / g,'-'). Replace (/ g,'_'). Replace (/ = / g,'') }, toBase64 (content) {return this.base64urlEscape (Buffer.from (JSON.stringify (content)). ToString ('base64'))}, encode (username,secret) {let header = this.toBase64 ({typ:' JWT', alg: 'HS256'}); let content = this.toBase64 (username); let sign = this.sign ([header,content] .join ('.), secret) Return [header,content,sign] .join ('.')}, base64urlUnescape (str) {str + = new Array (5-str.length% 4). Join ('='); return str.replace (/\-/ g,'+'). Replace (/ _ / g,'/');}, decode (token,secret) {let [header,content,sign] = token.split ('.') Let newSign = this.sign ([header,content] .join ('.'), secret); if (sign = newSign) {return Buffer.from (this.base64urlUnescape (content), 'base64'). ToString ();} else {throw new Error (' tampered')}
Ten. Advantages and disadvantages of JWT
JWT is not encrypted by default, but it can be encrypted. After the original token is generated, you can use the changed token to encrypt it again.
When JWT does not encrypt methods, some private data cannot be transmitted over JWT.
JWT can be used not only for authentication, but also for information exchange. Making good use of JWT can help reduce the number of times the server requests a database.
The biggest disadvantage of JWT is that the server does not save session state, so it is not possible to cancel tokens or change token permissions during use. In other words, once the JWT is issued, it will remain valid during the validity period.
JWT itself contains authentication information, so once the information is compromised, anyone can get all the privileges of the token. In order to reduce embezzlement, the validity period of JWT should not be set too long. For some important operations, users should authenticate every time they use them.
To reduce embezzlement and theft, JWT does not recommend using the HTTP protocol to transmit the code, but using the encrypted HTTPS protocol for transmission.
At this point, the study of "what is the principle of using NodeJS to achieve JWT" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.