Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use JWT in nodejs

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "how to use JWT in nodejs". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to use JWT in nodejs" can help you solve the problem.

What is JWT?

JWT is the abbreviation of JSON Web Token, which is an authentication solution in the network application environment. In the traditional authentication mechanism, it is nothing more than the following steps:

1. The user sends the account password to the server; 2. After verifying the account password, the server will save some user-related information, user role or expiration time in the current session. 3. The server gives the user a session_id, writes the user's Cookie or the client saves it locally; 4. Users need to bring this session_id every time they request a service, perhaps through Cookie or other ways. 5. After the server receives it, it goes back to the database to query the current session_id to verify whether the user has permissions.

One advantage of this mode is that the server can terminate the user's permissions at any time and can go to the database to modify or delete the current user's session information. But the downside is that if it is a server cluster, all machines need to share this session information to ensure that each server can get the same session storage information. Although these problems can be solved, the amount of engineering is huge.

The advantage of the JWT solution is that it does not save the information. The token data is saved on the client side, and only needs to be verified each time the request is accepted.

The principle of JWT

Briefly speaking, the principle of JWT is that when the client sends a request for authentication, the server generates a JSON object after authenticating the user, which probably includes information such as "who you are, what you do, etc., expiration time". The important thing is that there must be an expiration time. The approximate format is as follows:

{username: "Thief string er", role: "World Code Farmer", endTime: "May 20, 2022"}

However, it will not be sent to you in such a superficial way. It will be signed and transmitted through a reversible signature algorithm through the developed signature algorithm and some information of the payload you submitted. The approximate format is represented by an image:

As can be seen from the image, the returned information is roughly divided into three parts. On the left is the result after the signature, that is, the result returned to the client, and on the right is the source code of Decoded. The three parts are separated by "dots" and correspond one to one by red, purple and cyan respectively:

The first red part is the method that is mainly specified in Header,Header. The signature algorithm in the figure (default HS256) is HMAC with SHA-256, which is a symmetric algorithm. Only one key is shared between the two parties, and the typ field is identified as JWT.

The second purple part, payload, is a JSON object, that is, the data to be transferred. Officially, there are seven fields that can be used:

Iss (issuer): issuer

Exp (expiration time): expiration time

Sub (subject): topic

Aud (audience): audience

Nbf (Not Before): effective time

Iat (Issued At): time of issue

Jti (JWT ID): number

In addition to these fields, you can also make some custom fields, because JWT is unencrypted by default, so try to be careful not to use sensitive data when using it.

The third part is the Signature signature, which is the secret key specified by you and only exists on the server, and then uses the algorithm specified in the header to sign through the signature method below.

Simple use of JWT

Let's take a look at the specific use:

Step 1: we need to build a nodejs project; initialize a project with npm init-y; then we need to install dependencies, such as express, jsonwebtoken, and nodemon:

$npm i express jsonwebtoken nodemon

Then add the nodemon app.js command to the scripts field in package.json:

"scripts": {"start": "nodemon app.js"}

Step 2: initialize the node application and create the app.js file in the root directory

/ / app.jsconst express = require ("express"); const app = express (); app.use (express.json ()); app.listen (3000, () = > {console.log (3000 + "listening..."); / / listen for port 3000})

Step 3: introduce jsonwebtoken dependency and create the interface and the private key of the server

/ / app.js//...const jwt = require ("jsonwebtoken"); const jwtKey = "~! @ # $% ^ & * () +," / /.

The jwtKey in this file is our custom private key saved only in the server. After that, we start to write a / login interface to log in, and create a local simulation database for verification, and use the jwt.sign method to verify the signature:

/ / app.jsconst database = {username: "username", password: "password",}; app.post ("/ login", (req, res) = > {const {username, password} = req.body If (username = database.username & & password = database.password) {jwt.sign ({username,}, jwtKey, {expiresIn: "30s",}, (_, token) = > {res.json ({username, message: "login successful", token,});});}})

In the above code, we create a database variable to simulate the creation of a local account password database to verify the login. Next, we set up a post interface / login. After verifying that the account passwords match exactly, we sign through the human sign method under the jwt object imported by the jsonwebtoken package. This method has three API signatures:

Export function sign (payload: string | Buffer | object, secretOrPrivateKey: Secret, options?: SignOptions,): string;export function sign (payload: string | Buffer | object, secretOrPrivateKey: Secret, callback: SignCallback,): void;export function sign (payload: string | Buffer | object, secretOrPrivateKey: Secret, options: SignOptions, callback: SignCallback,): void

Here we use function overloading to implement the interface. Here we will implement the last interface signature. The first parameter can be a custom object type, a Buffer type, or a string type directly. Our source code uses the object type and customizes some fields, because jwt will also sign these data when signing, but it is worth noting that Try not to use sensitive data here, because JWT is unencrypted by default, and its core is signature to ensure that the data has not been tampered with, and the process of checking signatures is called verification.

Of course, you can also encrypt the original Token and transmit it.

The second parameter is the key we keep in the server for signing. Usually in the client-server mode, JWS uses the HS256 algorithm provided by JWA to add a key, which strictly depends on the key, but in a distributed scenario, multiple services may need to verify JWT. If the key is to be stored in each service, the security will be greatly compromised. You know, once the key is leaked. Anyone can forge JWT at will.

The third parameter: the option SignOptions for signature, and the signature of the API:

Export interface SignOptions {algorithm?: Algorithm | undefined; keyid?: string | undefined; expiresIn?: string | number | undefined; / * * expressed in seconds or a string describing a time span [zeit/ms] (https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" * / notBefore?: string | number | undefined; audience?: string | string [] | undefined; subject?: string | undefined; issuer?: string | undefined; jwtid?: string | undefined; mutatePayload?: boolean | undefined; noTimestamp?: boolean | undefined; header?: JwtHeader | undefined; encoding?: string | undefined;}

Here we use the expiresIn field, which specifies the expiration time. Refer to this document for how to use it.

The fourth parameter is a callback, and the second parameter of the callback is the token generated by signature. Finally, the token is returned to the frontend so that it can be stored locally in the frontend and brought to the server for verification.

Next, let's verify this interface: I installed the REST Client plug-in in vscode, and then created a request.http file in the root directory with the requested information written in it:

POST http://localhost:3000/logincontent-type: application/json {"username": "username", "password": "password"}

Then execute the npm run start command on the command line to start the service, and then click the Send Request button above the requset.http file to send the request:

After the request is successful, you will see a response message like this:

The token field is the token generated by our JWT

Let's verify whether the token is valid. We are writing an interface after login:

App.get ("/ afterlogin", (req, res) = > {const {headers} = req; const token = headers ["authorization"] .split (") [1]; / put token in the authorization field of header jwt.verify (token, jwtKey, (err, payload) = > {if (err) return res.sendStatus (403); res.json ({message:" Certification successful ", payload});});})

In this code, the previously generated token is obtained by getting the token in the authorization field in the request header. Then verify whether the token is valid by calling the jwt.verify verification method, which has three parameters:

/ / with four API signatures, you can check the document export function verify (token: string, / / the token secretOrPublicKey to be verified: Secret | GetPublicKeyOrSecret, / / the signature key callback?: VerifyCallback defined in the server, / / the callback for obtaining the verification information result): void

Next, let's copy the token we just responded to into the request header:

# GET http://localhost:3000/afterloginauthorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InVzZXJuYW1lIiwiaWF0IjoxNjUyNzg5NzA3LCJleHAiOjE2NTI3ODk3Mzd9.s9fk3YLhxTUcpUgCfIK4xQN58Hk_XEP5y9GM9A8jBbY

The previous Bearer authentication is the standard authentication method in http protocol.

Also click Send Request. When you see the response of the following image, it means the response is successful:

In fact, these are some simple uses of JWT, and then talk about the advantages and disadvantages of JWT itself.

The deficiency of JWT

JWT actually takes up a lot of storage space. If we need to sign too much information, then token will probably exceed the length limit of cookie. For example, compare these two images:

Obviously, as the amount of information in payload increases, so does the length of token.

Security, in fact, if token takes up too much space, the maximum storage space of Cookie can only be stored in local storage such as localStorage, but it will bring a problem. If it is not placed in cookie, security will be greatly reduced, and there will be the risk of getting it through js scripts, which means that any hacker can do anything with it.

Inflexible timeliness, in fact, some significance of JWT is that the user token does not need persistent storage, but uses server verification to effectively verify the token. As we have just seen, the signature is also signed with the expiration time. If you change the expiration time, the token will be tampered with. Because there is no storage and manual method to change the expiration time, it is difficult to delete this token immediately. If the user logs in twice, it is difficult to delete the token immediately. Generate two token, then in principle both token are valid

This is the end of the introduction to "how to use JWT in nodejs". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report