如何将 JWT 添加到授权标头?

2022-01-10 00:00:00 http-headers jwt authentication php

如下图所述,客户端需要在下一次请求时通过 Authorization Headerjwt 发送回服务器.

As described in the following slide, it is necessary that the client sends the jwt back to the server by an Authorization Header at the next request.

但是如何定义 Authorization Header 并将 JWT 添加到服务器?

But how can I define the Authorization Header and add the JWT to the server?

我现在的状态是:

  1. 用户通过 POST 请求向服务器发送 usernamepassword.
  2. 服务器创建JWT.
  3. 服务器将签名后的 JWT 发送回客户端,并将其保存在 cookie 中.
  1. User sends username and password to the server by a POST request.
  2. The server creates the the JWT.
  3. The server sends the signed JWT back to the client and saves it in a cookie.

现在我的问题:

  • 登录时:

据我了解,现在有必要将 JWT 发送回服务器.服务器验证令牌并将其发回以完成登录过程.

As I understand it, now its necessary to send the JWT back to the server. The server verifies the token and sends it back to finish the login process.

如何将 JWT 添加到 Authorization Header?

如果运行进程并从计算中接收数据:

我是否理解正确,客户端必须将 JWT 从登录发送到服务器,然后将第二个 JWT 与数据一起发送;或者我可以通过 POST 请求发送数据吗?

Do I understand right, that the client has to send the JWT from the login to the server and a second JWT with the data; or can I send the data by POST request?

推荐答案

所以,你对 JWT 来说是非常正确的.从客户端向服务器发送数据时(在创建 JWT 之后),您需要做的就是将其添加到请求标头中.许多人会尝试与 OAuth 保持相同的路径,并添加类似于以下节点片段的 Bearer 令牌:

So, You are pretty much correct with JWT. All you need to do when sending data from client to server (after JWT creation), is to add it to the request header. Many folks will try to keep along the same path as OAuth and add a Bearer token similar to the node snippet below:

var rp = require('request-promise');
options = {
  method: GET,
  uri: 'https://www.example.com/api/sample',
  headers: {
    Authorization: "Bearer <insert_your_JWT_here>"
  }
}
rp(options).then(function(res){
  <handle_response>
}

当然,我知道你提到了 PHP,但工作流程是一样的,只是语法不同.

Granted I know you mentioned PHP, but the workflows are the same, its just the syntax is different.

现在,要验证此令牌是否存在,服务器需要verify() 确认令牌对于已定义的秘密有效.在客户端发出的每个请求中,对于授权端点,您每次都需要发送此令牌.

Now, to verify that this token is present, the server would need to verify() that the token is valid with the secret that was defined. In every request made by the client, for an authorized endpoint, you would need to send this token everytime.

相关文章