在 Postman 的后续请求中使用身份验证令牌 [英] Use authentication token in follow-up requests in Postman
问题描述
我的应用 API 需要通过身份验证令牌进行身份验证.简而言之,我们向 /authentication
端点发送请求,它会以包含令牌的 JSON 对象进行响应,例如:
{"token": "xxxxxxxxxxxxxxxxxxxxxxxx"}
我们应用程序中的每个其他 API 端点都需要一个包含此令牌的 authentication
标头.现在,在 Postman 中,可以执行身份验证请求、复制令牌、打开下一个端点并手动粘贴 authentication
标头.但是在测试大量端点时,这变得乏味且耗时.
有没有办法让 Postman 保存并在任何后续请求中自动添加来自一个请求的 authentication
令牌?
更好的是,Postman 是否可以在任何其他请求之前自动发送 /authentication
请求?
Postman 在制作 API 请求时为您提供多种选择.
在您的情况下,您可以在收到令牌时为您的令牌创建一个全局变量:
var jsonData = JSON.parse(responseBody);postman.setGlobalVariable('token', jsonData.token);
这将进入您的 Tests
标签,以便在您的请求完成后执行此脚本.
现在,全局变量 token
已设置,并且可以在您发出的以下 API 请求中使用 {{token}}
语法进行访问.
我会用一个类似的例子向你演示一下:
1、将经纬度数据保存到全局变量lat
和long
中.2.通过引用变量的名称重用数据,即lat
和long
,将它们括在花括号中,如{{lat}}
和 {{long}}
.
- 您还可以管理这些全局变量,方法是单击右上角的齿轮图标,选择管理环境,然后打开全局选项卡.
- 提示:您也可以将获取令牌的请求保存到您的集合中,这样您就不必每次都制作 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}}
.
- 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.
- 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.
这篇关于在 Postman 的后续请求中使用身份验证令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!