Home Web Front-end Front-end Q&A what is nodejs jwt

what is nodejs jwt

Nov 23, 2021 pm 04:52 PM
jwt nodejs

In nodejs, the full name of jwt is Json web token, which is an open standard based on JSON implemented to transfer statements between network application environments. JWT claims are generally used to pass authenticated user identity information between identity providers and service providers in order to obtain resources from resource servers.

what is nodejs jwt

The operating environment of this tutorial: windows7 system, nodejs version 12.19.0, DELL G3 computer.

What is JWT in nodejs

Json web token (JWT) is a type of execution that is used to transfer claims between network application environments Based on the JSON open standard (RFC 7519). The token is designed to be compact and secure, especially suitable for single sign-on (SSO) scenarios on distributed sites.

JWT claims are generally used in The authenticated user identity information is passed between the identity provider and the service provider in order to obtain resources from the resource server. Some additional declaration information necessary for other business logic can also be added. The token can also be used directly for authentication, or Can be encrypted.

JWT, performs identity authentication during HTTP communication.

We know that HTTP communication is stateless, so the client’s request After the server is processed, it cannot be returned to the original client. Therefore, the accessed client needs to be identified. The common method is through the session mechanism: after the client successfully logs in to the server, the server will generate a sessionID and return To the client, the client saves the session ID in the cookie. When making a request again, it carries the session ID in the cookie to the server. The server will cache the session. When the client request comes, the server will know Which user's request is it, and the processing result is returned to the client to complete the communication.

Through the above analysis, we can know that the session has the following problems:

1. The session is saved on the server side , when the number of customer visits increases, the server needs to store a large number of sessions, which is a great test for the server;

2. When the server is a cluster, and the user logs in to one of the servers, the server will be The session is saved in the memory of the server, but when the user accesses other servers, it will be inaccessible. Cache consistency technology is usually used to ensure that it can be shared, or a third-party cache is used to save the session, which is inconvenient.

How is Json Web Token made?

1. The client logs in to the server through user name and password;

2. The server The client's identity is verified;

3. The server generates a Token for the user and returns it to the client;

4. The client saves the Token to the local browser, usually in a cookie ;

5. When the client initiates a request, it needs to carry the Token;

6. After the server receives the request, it first verifies the Token and then returns the data.

Server There is no need to save the Token, only the information carried in the Token needs to be verified;

No matter which server the client accesses in the background, as long as the user information can be verified.

What does Json Web Token look like?

You can tell from the name that it is a json.

is composed of three parts:

Header (header), generally use the default one with few changes:

{
 ‘typ’:‘JWT’,
 ‘alg’:‘HS256’
 }
Copy after login

(playload), everything is Installed here, the default content is:

{
 ‘iss’:‘签发者’,
 ‘sub’:‘面向的用户’,
 ‘aud’:‘接收方’,
 ‘exp’: 过期时间,
 ‘iat’: 创建时间,
 ‘nbf’: 在什么时间之前,该Token不可用,
 ‘jti’:‘Token唯一标识’
 }
Copy after login

Users can define it according to their needs. The content transmitted in the Token will generally put the user name, role and other information into the Token.

(signature), after the first two parts are converted into strings, use base64 encoding, and then encrypt to obtain a string.

Token = header (base64) payload (base64) signature;

what is nodejs jwt

Implementation process

–> When the user logs in, the server generates a token (encrypted string) and sends it to the front end.

–> The front end saves the token (save it wherever you want) Which)

–> When the front end initiates a data request, it carries the token

–> The server verifies whether the token is legal, continues the operation if it is legal, and terminates the operation if it is illegal

token Usage scenarios: stateless request, maintaining user login status, third-party login (token auth2.0)

Support algorithm

alg参数值数字签名或MAC算法
HS256使用SHA-256哈希算法的HMAC
HS384使用SHA-384哈希算法的HMAC
HS512使用SHA-512哈希算法的HMAC
RS256使用SHA-256哈希算法的RSASSA-PKCS1-v1_5
RS384使用SHA-384哈希算法的RSASSA-PKCS1-v1_5
RS512使用SHA-512哈希算法的RSASSA-PKCS1-v1_5
PS256使用SHA-256哈希算法的RSASSA-PSS(仅节点^ 6.12.0 OR> = 8.0.0)
PS384使用SHA-384哈希算法的RSASSA-PSS(仅节点^ 6.12.0 OR> = 8.0.0)
PS512使用SHA-512哈希算法的RSASSA-PSS(仅节点^ 6.12.0 OR> = 8.0.0)
ES256使用P-256曲线和SHA-256哈希算法的ECDSA
ES384使用P-384曲线和SHA-384哈希算法的ECDSA
ES512使用P-521曲线和SHA-512哈希算法的ECDSA
没有不包含数字签名或MAC值

开发时使用

安装

npm install jsonwebtoken --save
Copy after login

使用

const jwt = require('jsonwebtoken');//加载包
//产生token默认算法hs256
let token=jwt.sign({user:'123'},'123114655sad46aa');//此方法接收两个参数,第一个是要加密保存的数据(一个对象,不要放隐秘性的数据,如密码),第二个是要加密的私钥(一个字符串,越乱越好)
console.log(token);//返回一个加密字符串
// 服务器签发的token
//eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiMTIzIiwiaWF0IjoxNTcwMDc2NjU5fQ.3FT6v8zVptdWGBILD1m1CRY6sCP1I3E947krUh_E3



//客户端请求数据的时候验证token
//客户端传递过来的token
let tokens=token;

jwt.verify(tokens,'123114655sad46aa',function (err,data) {
    //verify接收两个参数,第一个参数是客户端传递过来的token,第二个参数是加密时的私钥;第三个参数是回调函数
    console.log(err);//签名通过返回null,签名不通过返回err(JsonWebTokenError: invalid signature)	
    console.log(data);//	通过返回解密数据,失败返回unfinished
});
Copy after login

更多node相关知识,请访问:nodejs 教程!!

The above is the detailed content of what is nodejs jwt. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

Which one to choose between nodejs and java? Which one to choose between nodejs and java? Apr 21, 2024 am 04:40 AM

Node.js and Java each have their pros and cons in web development, and the choice depends on project requirements. Node.js excels in real-time applications, rapid development, and microservices architecture, while Java excels in enterprise-grade support, performance, and security.

Can nodejs write front-end? Can nodejs write front-end? Apr 21, 2024 am 05:00 AM

Yes, Node.js can be used for front-end development, and key advantages include high performance, rich ecosystem, and cross-platform compatibility. Considerations to consider are learning curve, tool support, and small community size.

See all articles