[英]Storing and Using JWT & Secret Key
I have a login route for my app. 我有我的应用程序的登录路线。 I use
jwt tokens
to protect routes, but I have trouble to understand fully usage of secret key
. 我使用
jwt tokens
来保护路由,但是我很难理解secret key
充分使用。
I tought I need to use secret key to verify jwt
. 我需要使用秘密密钥来验证
jwt
。 Whenever user logs in, I send JWT Token
and Secret key
to user. 每当用户登录时,我都会向用户发送
JWT Token
和Secret key
。 JWT
is stored in local storage (phone or app storage) JWT
存储在本地存储(电话或应用程序存储)中
What should I about secret key? 我应该如何处理密钥? Should I both store to local and database?
我是否都应该存储到本地和数据库?
Login Route 登录路线
api.post('/api/login', (req, res) => {
var secretKey;
require('crypto').randomBytes(48, function(err, buffer) {
secretKey = buffer.toString('hex');
//Create JWT and Secret Key
jwt.sign({user}, secretKey, {expiresIn: '30s'}, (err, token) => {
res.json({
access_token : token,
secret_key : secretKey
});
});
});
}); });
Response After Login 登录后响应
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoxLCJ1c2VybmFtZSI6ImV4YW1wbGV1c2VyIiwiZW1haWwiOiJleGFtcGxlQGdtYWlsLmNvbSJ9LCJpYXQiOjE1NTExMTE1ODAsImV4cCI6MTU1MTExMTYxMH0.aSTVC-HcEdrH1KBNtuD_MoLZ8DWnSiM6bCqO4EgJ5zM",
"secret_key": "2e6a98abb5b23339ad14601d3bedc1d23847498cb18daf8cfc98c2a2095ec8f47d80053f6d4e22b8f6419407ac3083dc"}
Your secret key should never be given to anyone else. 您的秘密密钥绝不应该提供给其他任何人。 You need to keep this key a secret.
您需要将此密钥保密。 You can use the secret key to sign and issue tokens.
您可以使用密钥来签名和发行令牌。 It can also be used to validate tokens, but using your secret key to validate tokens is generally a bad idea because you then need to send the secret key to the service that is validating the token, which goes against the advice in my first two sentences.
它也可以用于验证令牌,但是使用您的秘密密钥来验证令牌通常是一个坏主意,因为您随后需要将秘密密钥发送到正在验证令牌的服务,这违反了我前两句话的建议。 。
If your secret key is asymmetrically signed, you can generate a public key based on the secret (private) key in the form of what's called a JSON Web Key ( read about JWKs here ). 如果您的秘密密钥是非对称签名的,则可以基于所谓的JSON Web密钥( 在此处了解JWK )的形式,基于秘密(私有)密钥生成一个公共密钥。 That public key can then be given to anyone in the universe and the public key can be used to verify the JWT only;
然后可以将该公共密钥提供给Universe中的任何人,并且该公共密钥只能用于验证JWT。 the public key cannot be used to sign new tokens.
公钥不能用于签名新令牌。
This means that you should only store the secret key in one location and that should be on your auth server that signs and issues tokens. 这意味着您只能将密钥存储在一个位置,并且该密钥应该在用于签名和颁发令牌的身份验证服务器上。 Read more about asymmetric key signing here
在此处阅读更多有关非对称密钥签名的信息
You should never send back to the client the secret key. 您绝不应该将密钥发送回客户端。 You have to store the secret key in your server.
您必须将密钥存储在服务器中。 You need it to sign and to verify jwt tokens.
您需要它来签名和验证jwt令牌。
This should be the flow: 这应该是流程:
Read more about JWT at https://jwt.io/ 在https://jwt.io/上了解有关JWT的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.