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.
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’ }
(playload), everything is Installed here, the default content is:
{ ‘iss’:‘签发者’, ‘sub’:‘面向的用户’, ‘aud’:‘接收方’, ‘exp’: 过期时间, ‘iat’: 创建时间, ‘nbf’: 在什么时间之前,该Token不可用, ‘jti’:‘Token唯一标识’ }
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;
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
使用
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 });
更多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!

To integrate React into HTML, follow these steps: 1. Introduce React and ReactDOM in HTML files. 2. Define a React component. 3. Render the component into HTML elements using ReactDOM. Through these steps, static HTML pages can be transformed into dynamic, interactive experiences.

React’s popularity includes its performance optimization, component reuse and a rich ecosystem. 1. Performance optimization achieves efficient updates through virtual DOM and diffing mechanisms. 2. Component Reuse Reduces duplicate code by reusable components. 3. Rich ecosystem and one-way data flow enhance the development experience.

React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor