使用JSON Web令牌jwt-simple进行API身份验证 [英] API authentication using json web tokens jwt-simple

查看:455
本文介绍了使用JSON Web令牌jwt-simple进行API身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jwt-simple创建api密钥.基本上,它所做的是encode(secret+data)并将其与请求一起发送.我知道服务器将decode(encode(secret+data))并确认它是有效请求. 在jwt-simple 文档中找到的示例代码:

I'm using jwt-simple to create an api key. Basically what it does is encode(secret+data) and sends it attaching with the request. I'm aware that the server will decode(encode(secret+data)) and verify that it is a valid request. Sample code found in jwt-simple documentation:

var jwt = require('jwt-simple');
var payload = { foo: 'bar' };
var secret = 'xxx';

// encode 
var token = jwt.encode(payload, secret);

// decode 
var decoded = jwt.decode(token, secret);
console.log(decoded); //=> { foo: 'bar' } 

我的问题是:

  • 如果某人知道encode(data+key)生成的令牌,将无法访问API?这就是为什么我应该在HTTP上使用HTTPS的原因?
  • 我认为我还需要在服务器上存储每个用户的机密,因为解密时需要使用它.如果我输入的不正确,应该在哪里存储?
  • 如何发送多个API请求?除了为每个请求发送API密钥之外,还有其他更好的方法吗?
  • Wouldn't someone be able to access the API if they know the token generated by encode(data+key)? Is that why I should use HTTPS over HTTP?
  • I think I need to store the secret of each user on the server as well, since it will be needed to decode. Where should I store it if I'm not correct?
  • How would I send multiple API requests? Is there a better way other than sending the API key for every request?

先谢谢了.

推荐答案

有关您与秘密的混淆,请参阅此帖子:

See this post regarding your confusion with the secret: Can anybody decode a JSON Web Token (JWT) without a secret key?

关于您的问题:

  1. 是的,每个设法获得有效令牌的人都可以访问您的API.因此,如果某人知道您用于签名令牌的秘密密钥并可以创建有效的有效负载,则可以使用该API.但是通常的流程是:用户登录,检查密码,如果密码正确,则给他一个有效的令牌.如果有人从该用户计算机上获取该令牌,那么您将无能为力.但是您可以使令牌过期,因此,如果有人偷了一个令牌,则该令牌在很长一段时间内都是无效的.

  1. Yes, everybody who somehow manages to get a valid token can access your API. So if someone knows the secret key you use for signing your tokens and can create a valid payload, he can use the API. But the usual flow would be: a user logs in, you check the password, if it's the right password you give him a valid token. If someone grabs that token from that users computer there is not much you can do. But you can make tokens expire so if someone steals one it is not valid for very long.

您可以使用相同的应用程序范围内的秘密对令牌进行签名,但是您将使用一些特定于用户的唯一有效负载,以便每个用户都获得不同的令牌.

You can sign your tokens with the same application wide secret but you would use some unique user specific payload so that every user gets a different token.

在一个简单的解决方案中,您只需在每次对API进行调用时将令牌发送给令牌(除了登录和注册外).建立会话还有其他解决方案,但我认为它们很难实施.

In a simple solution you would just send the token with every call you make to the API (besides login and sign-up). There are other solutions with establishing sessions but I think they are a bit more difficult to implement.

这篇关于使用JSON Web令牌jwt-simple进行API身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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