请求后端接口进行测试时,往往需要先登录,在 Apifox 中可以用“前置脚本”来完成登录操作,每次发请求测试接口前,都先调用“前置脚本”完成登录。
下面是一个例子(更多信息可参考登录态(Auth)如何处理),代码流程:
- 在环境变量中获取
LOGIN_USERNAME
和LOGIN_PASSWORD
变量的值(用户名和密码——需要自己先设置好) - 请求后端接口获取到公钥
- 使用公钥加密用户名和密码
- 使用加密后的用户名和密码请求后端登录接口,获得 Cookie 值
- 将 Cookie 值设置到请求头中
- 之后发起请求时就会带上 Cookie 值,后端就不会拦截请求
const username = pm.environment.get("LOGIN_USERNAME");
const password = pm.environment.get("LOGIN_PASSWORD");
login('session.id', 'ACCESS_TOKEN', username, password);
/**
* 登录并设置 Cookie 值
* @param {String} cookieKey Cookie 名
* @param {String} envName 用来保存 Cookie 值的全局变量名
* @param {String} username 用户名
* @param {String} password 用户密码
*/
function login(cookieKey = 'token', envName = 'ACCESS_TOKEN', username, password) {
const baseUrl = pm.request.getBaseUrl();
const publicKeyRequest = {
url: baseUrl + "/a/loginV2",
method: "POST"
};
// pm.sendrequest 参考文档:https://www.apifox.cn/help/app/scripts/api-references/pm-reference/#pm-sendrequest
pm.sendRequest(publicKeyRequest, function(err, res) {
if (err) {
console.log(err);
} else {
const result = res.json();
console.log(result);
if (result.code == 200 && result.msg == '已登录'){
console.log('已登录');
pm.request.headers.upsert({ key: 'Cookie', value: cookieKey + '=' + pm.environment.get(envName)})
return
}
if (result.code == 100) {
const publicKey = result.data;
const loginRequest = {
url: baseUrl + "/a/loginV2",
method: "POST",
body: {
mode: "urlencoded",
urlencoded: [
{ key: "keyA", value: encrypt(username, publicKey) },
{ key: "keyB", value: encrypt(password, publicKey) },
],
}
};
pm.sendRequest(loginRequest, function(err, res) {
if (err) {
console.log(err)
return
}
// Cookies 参考文档:https://www.apifox.cn/help/app/scripts/api-references/pm-reference/#pm-cookies
const result = res.json();
console.log(result);
if (result.code == 200 && result.msg == '已登录'){
console.log('已登录');
pm.request.headers.upsert({ key: 'Cookie', value: cookieKey + '=' + pm.environment.get(envName)})
} else {
console.log(envName, result.data);
pm.environment.set(envName, result.data);
// 参考:https://blog.csdn.net/m0_67401660/article/details/123419962
pm.request.headers.upsert({ key: 'Cookie', value: cookieKey + '=' + pm.environment.get(envName)})
}
});
}
}
});
}
/**
* RSA 加密,参考:https://blog.csdn.net/m0_67401660/article/details/123419962
* @param {String} encryptData 待加密值
* @param {String} publicKey 公钥
* @returns 加密后的值
*/
function encrypt(encryptData, publicKey) {
const jsrsasign = require("jsrsasign");
publicKey = "-----BEGIN PUBLIC KEY-----" + publicKey + "-----END PUBLIC KEY-----";
const pub = jsrsasign.KEYUTIL.getKey(publicKey);
const enc = jsrsasign.KJUR.crypto.Cipher.encrypt(encryptData, pub);
return enc;
}
标签:const,Postman,登录,publicKey,Cookie,result,Apifox,pm
From: https://www.cnblogs.com/Higurashi-kagome/p/17353996.html