基于 JWT 的身份验证的密钥是什么以及如何生成它? [英] What is secret key for JWT based authentication and how to generate it?

查看:18
本文介绍了基于 JWT 的身份验证的密钥是什么以及如何生成它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我开始使用基于 JWT 的身份验证.用户登录后,会生成一个用户令牌,如下所示

"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7Hg"

它由三个部分组成,每个部分用一个点(.)分隔.第一部分是 Base64 编码的标头.解码后我们会得到类似

<代码>{"alg": "HS256",//使用的算法典型":智威汤逊"}

第二部分是声明和 Base64 编码.解码后我们会得到类似的东西

<代码>{子":1234567890",名称":约翰·多伊",管理员":是的}

第三部分是签名,用

生成

HMACSHA256(base64UrlEncode(标题)+."+base64UrlEncode(有效负载),*秘密base64编码*)

现在这个密钥是什么?如何生成这个密钥?

我尝试了一些在线生成器,例如

一旦服务器接收到 JWT 以授予对受保护路由的访问权限,它需要对其进行验证以确定用户是否真的是他声称的那个人.换句话说,它将验证是否没有人更改令牌的标头和有效负载数据.同样,此验证步骤将检查是否没有第三方实际更改 Json Web 令牌的标头或负载.

那么,这种验证实际上是如何工作的?嗯,它实际上很简单.收到 JWT 后,验证将获取其标头和有效负载,并与仍保存在服务器上的秘密一起,基本上创建一个测试签名.

但是当初创建 JWT 时生成的原始签名还在令牌中,对吧?这就是验证的关键.因为现在我们要做的就是将测试签名与原始签名进行比较.而如果测试签名与原始签名相同,则说明payload和header没有被修改.

因为如果它们已被修改,那么测试签名就必须不同.因此,在这种数据没有更改的情况下,我们可以对用户进行身份验证.当然,如果两个签名实际上是不同的,好吧,那就意味着有人篡改了数据.通常通过尝试更改有效负载.但是操纵有效载荷的第三方当然无法访问机密,因此他们无法签署 JWT.所以原始签名永远不会对应于被操纵的数据.因此,在这种情况下,验证总是会失败.这是使整个系统正常工作的关键.正是这种魔力让 JWT 变得如此简单,但也非常强大.

现在让我们用 nodejs 做一些实践:

配置文件非常适合存储 JWT SECRET 数据.对签名使用标准 HSA 256 加密,密钥长度至少应为 32 个字符,但越长越好.

config.env:

JWT_SECRET = my-32-character-ultra-secure-and-ultra-long-secret//90天后JWT将不再有效,即使签名者正确并且一切都匹配.JWT_EXPIRES_IN=90

现在使用命令安装 JWT

npm i jsonwebtoken

用户注册后向他传递 JWT 令牌后的示例,以便他可以保持登录状态并获取资源的访问权限.

exports.signup = catchAsync(async (req, res, next) => {const newUser = await User.create({名称:req.body.name,电子邮件:req.body.email,密码:req.body.password,密码确认:req.body.passwordConfirm,});const token = jwt.sign({ id: newUser._id }, process.env.JWT_SECRET, {expiresIn: process.env.JWT_EXPIRES_IN,});res.status(201).json({状态:'成功',令牌,数据: {新用户,},});});

输出:

在我看来,不要求助于第三方来生成你的超级密钥,因为你不能再说它是秘密了.只需使用您的键盘即可.

Recently I started working with JWT based authentication. After user login, a user token is generated which will look like

"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ".

It consist of three parts each separated with a dot(.).First part is header which Base64 encoded. After decoding we will get something like

{
  "alg": "HS256", //Algorithm used
  "typ": "JWT"
}

Second part is claims and Base64 encoded. After decoding we will get something like

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

Third part is signature and is generated with

HMACSHA256(
    base64UrlEncode(header) + "." +
    base64UrlEncode(payload),
    *secret base64 encoded*
  )  

Now what is this secret key and how to generate this secret key??

I tried some online generator like "http://kjur.github.io/jsjws/tool_jwt.html" but dint get much help.

解决方案

A Json Web Token made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted.

So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server.

And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right? Then together with the header and the payload, these signature forms the JWT, which then gets sent to the client.

Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token.

So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.

But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature. And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified.

Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures are actually different, well, then it means that someone tampered with the data. Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT. So the original signature will never correspond to the manipulated data. And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple, but also extremely powerful.

Now let's do some practices with nodejs:

Configuration file is perfect for storing JWT SECRET data. Using the standard HSA 256 encryption for the signature, the secret should at least be 32 characters long, but the longer the better.

config.env:

JWT_SECRET = my-32-character-ultra-secure-and-ultra-long-secret
//after 90days JWT will no longer be valid, even the signuter is correct and everything is matched.
JWT_EXPIRES_IN=90

now install JWT using command

npm i jsonwebtoken

Example after user signup passing him JWT token so he can stay logged in and get access of resources.

exports.signup = catchAsync(async (req, res, next) => {
  const newUser = await User.create({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
    passwordConfirm: req.body.passwordConfirm,
  });
  const token = jwt.sign({ id: newUser._id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN,
  });

  res.status(201).json({
    status: 'success',
    token,
    data: {
      newUser,
    },
  });
});

output:

In my opinion, do not take help from a third-party to generate your super-secret key, because you can't say it's secret anymore. Just use your keyboard.

这篇关于基于 JWT 的身份验证的密钥是什么以及如何生成它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆