且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Postman 的后续请求中使用身份验证令牌

更新时间:2023-12-03 11:39:34

Postman 在制作 API 请求时为您提供多种选择.

在您的情况下,您可以在收到令牌时为您的令牌创建一个全局变量:

var jsonData = JSON.parse(responseBody);postman.setGlobalVariable('token', jsonData.token);

这将进入您的 Tests 标签,以便在您的请求完成后执行此脚本.

现在,全局变量 token 已设置,并且可以在您发出的以下 API 请求中使用 {{token}} 语法进行访问.

我会用一个类似的例子向你演示一下:

1、将经纬度数据保存到全局变量latlong中.2.通过引用变量的名称重用数据,即latlong,将它们括在花括号中,如{{lat}}{{long}}.

  1. 您还可以管理这些全局变量,方法是单击右上角的齿轮图标,选择管理环境,然后打开全局选项卡.
  2. 提示:您也可以将获取令牌的请求保存到您的集合中,这样您就不必每次都制作 URL 来获取令牌.

My app API requires authentication via an authentication token. In short, we send a request to a /authentication endpoint and it responds with a JSON object containing a token, like:

 {"token": "xxxxxxxxxxxxxxxxxxxxxx"}

Every other API endpoint in our application requires an authentication header containing this token. Now, in Postman it's possible to do the authentication request, copy the token, open the next endpoint and paste the authentication header in manually. But this becomes tedious and time-consuming when testing lots of endpoints.

Is there a way to have Postman save and automatically add the authentication token from one request in any follow-up requests?

Even better, could Postman automatically send the /authentication request prior to any of the other requests?

Postman allows you a wide variety of options when crafting API requests.

In your case, You can create a global variable for your token when you receive it by:

var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable('token', jsonData.token);

This would go in your Tests tab, in order to execute this script after your request has been completed.

Now, a global variable token is set and can be accessed using {{token}} syntax in the following API requests you make.

I'll demonstrate it to you regarding the same, with a similar example:

1. Save the data of latitude and longitude into the global variables lat and long. 2. Reuse the data by referring to the name of the variable, i.e. lat and long by enclosing them within curly braces like {{lat}} and {{long}}.

  1. You can also manage these global variables, by clicking on the gear icon in the top right corner, and selecting manage environments then opening the Globals tab.
  2. Tip: You can also, save the request to obtain the token into your collections, so that each time, you don't have to craft the URL to obtain the token.