其他两个答案都是正确的。但是,还有另一种方法可以做到这一点,并且不需要任何额外的请求。
此方法使用需要access_token 的请求的pre-request 脚本。
您可以使用pm.sendRequest 中记录的postman-sandbox-api
从预请求脚本只需向 auth-token URL 发送一个请求。发送所有凭据和刷新令牌。在响应中,您将获得访问令牌,然后您可以将其保留在环境中或仅在内存中,然后使用它。
示例代码
我在这里做了一个要点https://gist.github.com/harryi3t/dd5c61451206047db70710ff6174c3c1
// Set all these variables in an environment or at collection level
let tokenUrl = pm.variables.get('tokenUrl'),
clientId = pm.variables.get('clientId'),
clientSecret = pm.variables.get('clientSecret'),
refreshToken = pm.variables.get('refreshToken'),
requestOptions = {
method: 'POST',
url: tokenUrl,
body: {
mode: 'formdata',
formdata: [
{
key: 'grant_type',
value: 'refresh_token'
},
{
key: 'client_id',
value: clientId
},
{
key: 'client_secret',
value: clientSecret
},
{
key: 'refresh_token',
value: refreshToken
}
]
}
};
console.log({ requestOptions });
pm.sendRequest(requestOptions, (err, response) => {
let jsonResponse = response.json(),
newAccessToken = jsonResponse.access_token;
console.log({ err, jsonResponse, newAccessToken })
// If you want to persist the token
pm.environment.set('accessToken', newAccessToken);
// Or if you just want to use this in the current request and then discard it
pm.variables.set('accessToken', newAccessToken);
});
现在,当发送请求时,变量accessToken 将出现,您可以在请求中使用它,如下所示:
注意:Oauth2 中有 4 种授权类型。其中两个(身份验证代码和隐式)需要与无法自动化的浏览器交互。但是如果服务器提供了 refresh-token,那么上面的脚本可以帮助你获取 access-token。其他两种类型(客户端凭据和密码凭据)不需要任何浏览器交互。所以这些可以从脚本中自动化。如果您使用的是 client_credentials,则可以调整上述脚本以从 authUrl 获取 code,然后从 AuthTokenUrl 获取 access_token。