json转jwt
This article is written on the applications of JSON Web Tokens (JWTs) in a server-client relationship using Node.js and vanilla JavaScript. If you want to learn about the concepts behind JWT, I could not recommend Mariano Calandra’s Medium post more.
本文是使用Node.js和Vanilla JavaScript在服务器-客户端关系中介绍JSON Web令牌 (JWT)的应用程序的。 如果您想了解JWT背后的概念,我不能推荐Mariano Calandra的Medium post更多内容。
To install JSON Web Tokens in your project, run:
要在您的项目中安装JSON Web令牌,请运行:
$ yarn add jsonwebtoken
And import it into your files like so:
并将其导入到您的文件中,如下所示:
const jwt = require("jsonwebtoken");
验证令牌 (Authenticating a Token)
There are many ways to go about implementing a JWT authentication system in an Express.js application. What suites me best, though, it to utilize Express.js’ middleware functionality. How it works is when a request is made to a specific route, you can have the (req, res)
variables sent to an intermediary function before the one specified in the app.get((req, res) => {})
.
在Express.js应用程序中实现JWT身份验证系统有很多方法。 不过,最适合我的是利用Express.js的中间件功能。 它是如何工作的,当对特定路由发出请求时,您可以在app.get((req, res) => {})
指定的变量之前将(req, res)
变量发送给中间函数。
The middleware is a function that takes parameters of (req, res, next)
. The req
is the sent request (get, post, delete, use, etc.), the res
is the response that can be sent back to the user in a multitude of ways (res.sendStatus(200), res.json(), etc), and next
is a function that can be called to move the execution past the piece of middleware and into the actual app.get
server response.
中间件是一种函数,它接受(req, res, next)
。 req
是已发送的请求( get,post,delete,use等 ), res
是可以通过多种方式(res.sendStatus(200),res.json())发送回用户的响应。等),以及next
是一个可以被称为移动执行过去的中间件并进入实际功能app.get
服务器响应。
Here’s the middleware function I wrote for my auth needs:
这是我为身份验证需求编写的中间件功能:
function authenticateToken(req, res, next) {
// Gather the jwt access token from the request header
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[1]
if (token == null) return res.sendStatus(401) // if there isn't any token
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET as string, (err: any, user: any) => {
console.log(err)
if (err) return res.sendStatus(403)
req.user = user
next() // pass the execution off to whatever request the client intended
})
}
An example request using this middleware function would look something like this:
使用此中间件功能的示例请求如下所示:
GET https://mysite:4000/api/userOrders
Authorization: Bearer JWT_ACCESS_TOKEN
And, an example of a request that would use that piece of middleware would look like this:
并且,使用该中间件的请求示例如下所示:
// ...
app.get('/api/userOrders', authenticateToken, (req, res) => {
// executes after authenticateToken
// ...
})
// ...
生成令牌 (Generating a Token)
Backtracking, we’ll now discuss how to actually generate and send a JWT token to the client.
回溯,我们现在将讨论如何实际生成JWT令牌并将其发送到客户端。
To accomplish this (this being signing a token), you need to have 3 pieces of information:
要实现此目的(这是对令牌进行签名),您需要具备3条信息:
- The token secret 令牌的秘密
- The piece of data to hash in the token 要在令牌中散列的数据
- The token expire time 令牌到期时间
The token secret is simply a super long, super random string used to encrypt and decrypt the data. To generate this secret, I recommend using Node’s crypto
library, like so:
令牌密钥只是用于加密和解密数据的超长超随机字符串。 要生成此秘密,我建议使用Node的crypto
库,如下所示:
> require('crypto').randomBytes(64).toString('hex')
// '09f26e402586e2faa8da4c98a35f1b20d6b033c6097befa8be3486a829587fe2f90a832bd3ff9d42710a4da095a2ce285b009f0c3730cd9b8e1af3eb84df6611'
Be careful! If your ‘secret’ is simple, the token verification process will be much easier to break by an unauthorized intruder.
小心! 如果您的“秘密”很简单,则令牌验证过程将更容易被未经授权的入侵者破坏。
Now store this secret in the your project’s .env
file:
现在,将此秘密存储在项目的.env
文件中:
TOKEN_SECRET=7bc78545b1a3923cc1e1e19523fd5c3f20b409509...
To bring this token into a Node file and to use it, you have to use dotenv
:
要将此令牌带入Node文件并使用它,必须使用dotenv
:
const dotenv = require("dotenv");
// get config vars
dotenv.config();
// access config var
process.env.TOKEN_SECRET;
The piece of data that you hash in your token can be something as simple as a user ID or username, all the way up to a much more complex object. In either case, it should be an identifier for a specific user.
您在令牌中散列的数据可以像用户ID或用户名一样简单,一直到更复杂的对象。 无论哪种情况,它都应该是特定用户的标识符 。
The token expire time is a string, such as '1800s’ that details how long until the token will be invalid.
令牌到期时间是一个字符串,例如'1800s',它详细说明令牌将失效多长时间。
So, here’s a function for signing tokens:
因此,这是一个用于签名令牌的函数:
// username is in the form { username: "my cool username" }
// ^^the above object structure is completely arbitrary
function generateAccessToken(username) {
// expires after half and hour (1800 seconds = 30 minutes)
return jwt.sign(username, process.env.TOKEN_SECRET, { expiresIn: '1800s' });
}
This can be sent back from a request to sign in or log in a user.
可以从登录或登录用户的请求中发送回去。
app.post('/api/creteNewUser', (req, res) => {
// ...
const token = generateAccessToken({ username: req.body.username });
res.json(token);
// ...
});
客户端令牌处理 (Client-Side Token Handling)
When the client receives the token, they often want to store it for gathering user information in future requests. The most popular manner for storing auth tokens are cookies and localStorage. Here’s an implementation for storing a cookie using client-side JavaScript code:
当客户端收到令牌时,他们通常希望将其存储以在将来的请求中收集用户信息。 存储身份验证令牌的最流行方式是cookie和localStorage 。 这是使用客户端JavaScript代码存储Cookie的实现:
...
// get token from fetch request
const token = await res.json();
// set token in cookie
document.cookie = `token=${token}`
// ...
And with localStorage it’s just as easy:
借助localStorage,它变得非常简单:
const token = await res.json();
localStorage.setItem('token', token);
It’s that simple!
就这么简单!
翻译自: https://www.digitalocean.com/community/tutorials/nodejs-jwt-expressjs
json转jwt