【测试工具】postman自动 refresh token脚本

  1. 登录成功获取 token 接口后置脚本:
//获取当前时间
const d = new Date();
const nowTime = d.getTime();
//获取当前响应
const jsonData = pm.response.json()
//获取响应元素
const access_token = jsonData['access_token']
const refresh_token = jsonData['refresh_token']
const expires_in = jsonData['expires_in']
const refresh_expires_in = jsonData['refresh_expires_in']
const token_expires_timestamp = nowTime + expires_in * 1000;
const refresh_token_expires_timestamp = nowTime + refresh_expires_in * 1000;
//设置环境变量
pm.environment.set("access_token", access_token);
pm.environment.set("refresh_token", refresh_token);
pm.environment.set("expires_in", expires_in);
pm.environment.set("refresh_expires_in", refresh_expires_in);
pm.environment.set("token_expires_timestamp", token_expires_timestamp);
pm.environment.set("refresh_token_expires_timestamp", refresh_token_expires_timestamp);

//https需要使用,http可以忽略这步
const cookies = pm.response.headers.get('Set-Cookie')
pm.environment.set("cookies", cookies);
  1. 其他接口前置脚本:
// 定义发送登录接口请求方法
const baseUrl = pm.environment.get("BASE_URL");
const refreshToken = pm.environment.get("refresh_token");
const cookies = pm.environment.get("cookies");
const token_expires_timestamp = pm.environment.get("token_expires_timestamp");

const refreshTokenRequest = {
  url: baseUrl + "/refreshToken",
  method: "POST",
  // body 为 json 格式
  header: {
    "Authorization": refreshToken,
    "Content-Type": 'application/json',
    "Connection": "keep-alive",
    'User-Agent': 'Apifox/1.0.0 (https://www.apifox.cn)',
    "Cookie": cookies
  },
  body: {
    mode: 'raw',
    raw: JSON.stringify({ 
    }) 
  }   
};

//判断access_token是否过期了
const d = new Date()
const t = d.getTime()
if (t > token_expires_timestamp){
  // 过期了就发送refreshToken请求。
  pm.sendRequest(refreshTokenRequest, function(err, res) {
    if (res.code == 200) {
      const data = res.json()
      
      pm.environment.set('access_token', data['access_token'])
      pm.environment.set('refresh_token', data['refresh_token'])
      pm.environment.set('expires_in', data['expires_in'])
      pm.environment.set('refresh_expires_in', data['refresh_expires_in'])
      
      const token_expires_timestamp = t + data['expires_in'] * 1000;
      const refresh_token_expires_timestamp = t + data['refresh_expires_in'] * 1000;
      pm.environment.set("token_expires_timestamp", token_expires_timestamp);
      pm.environment.set("refresh_token_expires_timestamp", refresh_token_expires_timestamp);
      return
    } 
    console.log(res.code)
    console.log(refreshTokenRequest)
  });
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值