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

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

问题描述

最近,我开始使用基于JWT的身份验证.用户登录后,将生成一个用户令牌,该令牌将类似于

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

"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ".

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

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"
}

第二部分是声明并以Base64编码.解码后,我们将得到类似

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??

我尝试了一些在线生成器,例如" http://kjur.github.io/jsjws/tool_jwt .html " 但是有点帮助.

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

推荐答案

用于对JWT进行签名的算法(HS256)表示该机密是对称的密钥,发送方和接收方都知道.协商并带外分发.因此,如果您是令牌的预期接收者,则发送者应该已经为您提供了带外秘密.

The algorithm (HS256) used to sign the JWT means that the secret is a symmetric key that is known by both the sender and the receiver. It is negotiated and distributed out of band. Hence, if you're the intended recipient of the token, the sender should have provided you with the secret out of band.

如果您是发件人,则可以使用任意字节串作为机密,可以生成或有目的地选择它.您必须确保将秘密提供给带外的预期收件人.

If you're the sender, you can use an arbitrary string of bytes as the secret, it can be generated or purposely chosen. You have to make sure that you provide the secret to the intended recipient out of band.

为便于记录,JWT中的3个元素不是base64编码的,而是base64url-encoded的,这是base64编码的变体,可产生URL安全值.

For the record, the 3 elements in the JWT are not base64-encoded but base64url-encoded, which is a variant of base64 encoding that results in a URL-safe value.

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

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