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 node

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this article, the editor introduces in detail "how to use jwt in node". The content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to use jwt in node" can help you solve your doubts.

Introduction: because http is stateless, user identity information is not stored in the request response process, so there are many ways for users to identify and store user identity, such as cookie,session,jwt. An interface service I did recently uses jwt to store and manage user information. Compared with local cookie storage and server-side session storage, jwt becomes more secure and more economical and convenient. This paper makes a simple summary of the use of jwt in node services.

Introduction to jwt concept

JWT, whose full name is JSON Web Token, is an open standard RFC 7519 that defines a compact and self-contained way to securely transfer information between parties as JSON objects. JWT can use a key or a public / private key pair of RSA or ECDSA to sign, and the signature can be verified.

component

Jwt signature tokens generally consist of three parts, namely Header (header information), Payload (payload), and Signature (signature), such as xxxxx.yyyyy.zzzzz.

Header

Generally, the type of token and the signature algorithm are stored, such as:

{"alg": "HS256", "typ": "JWT"}

Payload

Generally, storage statements, that is, user information and attachment data, are divided into registration statements, public statements and private statements.

For example:

{"sub": "1234567890", "name": "John Doe", "admin": true}

Signature

Using signature algorithm to sign Header and Payload

For example:

HMACSHA256 (base64UrlEncode (header) + "." + base64UrlEncode (payload), secret)

Then a standard jwt signing token would be like this eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c.

Application scenario

User authorized access

For example, after a user logs in, the server issues a jwt token to the client. Every time the user requests data, the token is carried in the request header. The server can obtain the data after verification. This method has little overhead, does not need to be stored by the server, and can be used across domains.

information switching

Store encrypted information between the parties to verify whether the signature content has been tampered with.

Security.

Because tokens can be disassembled and the header and Payload inside can be parsed and seen, try not to store some private information in Payload.

Installation configuration

Let's use jwt in node to do something.

On the npm website, there are many jwt packages, you can choose what you think is appropriate.

Search for jwtNAME | DESCRIPTION | AUTHOR | DATE | VERSION | KEYWORDSjwt | JSON Web Token for... | = mattrobenolt | 2012-05-05 | 0.2.0 | express-jwt | JWT authentication... | = woloski... | | 2021-08-11 | 6.1.0 | auth authn authentication authz authorization http jwt token oauth expressjsonwebtoken | JSON Web Token … | | = dschenkelman... | | 2019-03-18 | 8.5.1 | jwtjwt-decode | Decode JWT tokens, … | | = jeff.shuman... | | 2020-11-16 | 3.1.2 | jwt browserpassport-jwt | Passport … | | = themikenichol... | | 2018-03-13 | 4.0.0 | Passport Strategy JSON Web Token JWTkoa-jwt | Koa middleware for … | | = stiang... | | 2021-09-24 | 4.0.3 | auth authn authentication authz authorization http jwt json middleware token oauth permissions koajsrsasign | opensource free … | | = kjur | 2021-12-01 | 10.5.1 | crypto cryptography Cipher RSA ECDSA DSA RSAPSS PKCS#1 PKCS#5 PKCS#8 private key public key CSR PKCS#10 hash function HMac ASN.1 certexpress-jwt-permissions | Express middleware... | = angryunicorn... | | 2021-08-18 | 1.3.6 | express middleware JWT permissions authorization token securitynjwt | JWT Library for … | | = robertjd | 2021-12-03 | 1.2.0 | jwtfastify-jwt | JWT utils for... | = starptech... | | 2021-12-03 | 4.1.0 | jwt json token jsonwebtoken fastifydid-jwt | Library for Signing … | | = simonas-notcat... | | 2021-12-03 | 5.12.1 | hapi-auth-jwt2 | Hapi.js … | | = nelsonic | 2020-09-08 | 10.2.0 | Hapi.js Authentication Auth JSON Web Tokens JWTauth0-lock | Auth0 Lock | = jeff.shuman... | | 2021-11-02 | 11.31.1 | auth0 auth openid authentication passwordless browser jwtjwks-rsa | Library to retrieve … | | = jeff.shuman... | | 2021-10-15 | 2.0.5 | jwks rsa jwtrestify-jwt-community | JWT authentication … | | = frbuceta | 2021-12-05 | 1.1.21 | auth authentication authorization http jwt token oauth restifydid-jwt-vc | Create and verify... | = simonas-notcat... | | 2021-11-23 | 2.1.8 | jwt-service | A simple wrapper … | | = nfroidure | 2021-11-01 | 8.0.0 | jwt knifecycleangular-jwt | Library to help you... | = jeff.shuman... | | 2019-03-20 | 0.1.11 | @ thream/socketio-jwt | Authenticate … | | = divlo | 2021-07-23 | 2.1.1 | socket socket.io jwtappstore-connect-jwt-gene | [! [NPM] (https://nod … | | = poad | 2021-10-15 | 1.0.1 | jwt appstorerator-core | install jwt |

Personally, I think this jsonwebtoken is very good, so I will use this package in this article.

Common usage of npm i jsonwebtoken

Signature

Signature syntax: jwt.sign (payload, secretOrPrivateKey, [options, callback]).

For example:

/ / General signature var jwt = require ('jsonwebtoken'); var token = jwt.sign ({foo:' bar'}, 'secret'); / / Private key signature var privateKey = fs.readFileSync (' private.key'); var token = jwt.sign ({foo: 'bar'}, privateKey, {algorithm:' RS256'}); / / set expiration time jwt.sign ({data: 'bar'},' secret', {expiresIn: 60 * 60}) / / 1h

Verification

Validation syntax: jwt.verify (token, secretOrPublicKey, [options, callback])

For example:

/ / General verification var decoded = jwt.verify (token, 'secret'); console.log (decoded.foo) / / bar// public key authentication var cert = fs.readFileSync (' public.pem'); jwt.verify (token, cert, function (err, decoded) {console.log (decoded.foo) / / bar})

Decode

Decoding syntax: jwt.decode (token [, options])

For example:

Var decoded = jwt.decode (token, {complete: true}); console.log (decoded.header); console.log (decoded.payload); encapsulation method

According to the method in the installation configuration, you can carry out secondary packaging according to your own needs, which is more suitable for your own method.

Introduce dependency packages and configurations

Const jwt = require ("jsonwebtoken"); const config = {secret: '2021123456, time: 60 * 60,}

Signature

Function create (data, time) {let token = jwt.sign (data, config.secret, {algorithm: "HS256", expiresIn: time | | config.time,}) return token;}

Verification

Function verify (token) {return jwt.verify (token, config.secret, function (err, decoded) {if (err) {return {code: 1, msg: 'invalid', data: null,}} else {return {code: 2, msg:' valid', data: decoded,})}

Decode

Function decoded (token, complete = true) {return jwt.decode (token, {complete,});}

The above is a relatively simple method, if you still want to use the public key and private key, you can use the one described in the installation configuration above.

Actual combat practice

After the above packaging method, you can come to the actual combat exercise, whether it is effective.

Create a new folder test, a new file index.js to store test cases, and jwt.js to store calling methods.

Mkdir testcd testnpm init-ynpm i jsonwebtoken

Jwt method

/ / jwt.jsconst jwt = require ('jsonwebtoken'); const config = {secret:' 2021123456signature, / / key time: 60Secret60, / / Expiration time} / / create signature token function create (data, time) {let token = jwt.sign (data, config.secret, {algorithm: 'HS256', expiresIn: time | | config.time,}); return token } / / verify token function verify (token) {return jwt.verify (token, config.secret, function (err, decoded) {if (err) {return {code: 1, msg: 'invalid', data: null,}} else {return {code: 2, msg:' valid', data: decoded })} / / Decode token function decoded (token, complete = true) {return jwt.decode (token, {complete,}) } const token = {create, verify, decoded,} module.exports = token

Create token, verify token, decode token

/ / index.jsconst jwt = require ('. / jwt'); / / generate token let token = jwt.create ({'id': 1,' name': 'mark'}, 60' 60'2); console.log (token); / * eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwibmFtZSI6Im1hcmsiLCJpYXQiOjE2MzkxMDYyNzMsImV4cCI6MTYzOTExMzQ3M30.20O1r0NVMf-j-9RwNcgls9ja0n1rGqSKN51_cRcvpE8*/// verification token let verifyRes = jwt.verify (token); console.log (verifyRes) / * {code: 2, msg: 'valid', data: {id: 1, name:' mark', iat: 1639106273, exp: 1639113473} * / / Decode token let deRes = jwt.decoded (token, true); console.log (deRes) / * {header: {alg: 'HS256', typ:' JWT'}, payload: {id: 1, name: 'mark', iat: 1639106273, exp: 1639113473}, signature:' 20O1r0NVMf Lashi 9RwNcgls9ja0n1rGqSKN51promocRcvpE8'} * /

Run the command node index.js to test whether it is correct.

After reading this, the article "how to use jwt in node" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, please follow the industry information channel.

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