You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

REST Assured传递表单参数时遭遇会话失效问题求助

问题描述

使用Java编写REST Assured接口测试代码调用/admin/faxer/的POST接口时,已配置含x-auth-token的请求头并传递formParam参数,但每次运行都返回400错误,提示**"You are already logged out. Please login again"**。

代码片段

// First convert data table to the String map.
Map<String, String> map = tableData.asMap(String.class, String.class);

// We need headers params for this request. So first we are making headers params map for passing it to the request.
HashMap<String, String> header_params = new HashMap<>();
header_params.put("x-auth-token", getValueFromPropertyFile(PropertyFileKeys.X_AUTH_TOKEN));

// Add content type as form-data.
header_params.put("Content-Type", "application/json");

// Get the SIP Device number based on the customer id.
String sip_device_number = FaxerUsefullResource.getSIPDeviceNumberForCustomerAccount(admin_login_token,customer_id);
print("SIP Device number of customer account id : "+customer_id+" is : " + sip_device_number);

// Build the request specification.
RequestSpecification request_specification_builder = new RequestSpecBuilder()
        // Set the Base Uri. Value of baseURL we are taking from the "config.properties" file.
        .setBaseUri(getValueFromPropertyFile(PropertyFileKeys.BASE_URL))
        // Set up the header params.
        .addHeaders(header_params)
        // Build entire request specification.
        .build();

// Make the Request specification from the built request specification.
request_specification = given()
        // Bind the built configuration with request.
        .spec(request_specification_builder)
        // Add form data parameter with values.
        .formParam("id","1")
        .formParam("token",admin_login_token)
        .formParam("action","faxer_create")
        .formParam("sip_device",sip_device_number)
        .formParam("fax_number",map.get("fax_number"))
        .formParam("fax_type",map.get("fax_type"))
        .formParam("description",map.get("description"));

// Calling the request and store the response for further verification.
response = hit_https_request_and_return_response("FaxerAPI", API_method, request_specification);

请求响应详情

SIP Device number of customer account id : 412 is : 2540285577
Resource name : FaxerAPI
End point : /admin/faxer/
Request method: POST
Request URI:    https://alpha.astppbilling.org/admin/faxer/
Proxy:          <none>
Request params: <none>
Query params:   <none>
Form params:    id=1
                token=OTlEckI5QjJBb3dCMy9vM0EwZDM2dz09
                action=faxer_create
                sip_device=2540285577
                fax_number=0001
                fax_type=1
                description=APIAutomationDescription
Path params:    <none>
Headers:        x-auth-token=PRLgav3UWUAkh5OAL6zL6EizBuRm37Ok
                Accept=*/*
                Content-Type=application/json
Cookies:        <none>
Multiparts:     <none>
Body:           <none>
HTTP/1.1 400 
Server: nginx/1.18.0
Date: Wed, 09 Nov 2022 06:16:10 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: ITPLATPci_session=a%3A0%3A%7B%7D; expires=Tue, 09-Nov-2021 16:16:10 GMT; Max-Age=0; path=/
Set-Cookie: ITPLATPci_session=B2ECYFUzBGkHeABzUTUFOAM7Vj4HJVEgUmJQJQIlAm0GNFNtBAxRalEyVC4BaQAkAD4AM1Q4ADZWfF1tUWACNFdkUm0FNwEzAWxTNwM1UTIHOQI5VTcEZAc0AGZRPwU6Az9WMgc%2BUTVSY1BvAm8CYgZvU2IEYlFlUWFULgFpACQAPgAxVDoANlZ8XWZRIQJfV2NSMAU1AXUBOVNwAydRIQc7AilVPARiBzcAOlEtBTgDOlYzBylRYVI1UGUCeAIyBm9TLQRiUTpRZVQuAWkAJAA%2BADFUOgA2VnxdelEiAmVXcFILBTABYAE5U20DIFEhBzsCKVU8BGAHOgA6US0FSAN7VmUHZFE7UmJQewIeAnAGL1NzBBBRb1E%2FVGkBPAAjACsANFQkADlWcF0%2BUWICIFcqUh4FMAFxAT1TLANlUTIHLgJqVSgEYgcwAClRLQUyA3hWPgc2UWBSPVB0AjoCZQYoU3cEDFFiUTVUeAE7ACEAbQB0VHMALlZlXWZRawIxVzRSYgVmAT4Ba1M3A2FRNAcwAmFVdQRpBzoAOlEtBXwDeFZhB3VRDFJjUDcCIgJlBnlTOAQgUTlRZlQ2AXAAdQA%2FAH0%3D; expires=Wed, 09-Nov-2022 08:16:10 GMT; Max-Age=7200; path=/
Set-Cookie: ITPLATPci_session=AWdXNVYxCmdQLwR3UjYHOggwUztRc1EgUGBWIw0qUD9dbwE%2FBw8FPlEyWSNaMgouBTsAM1Y6BzECKFRkBzYHMQo5CjUENlFjVDkBZQE3DG8BP1dsVjQKalBjBGJSPAc4CDRTN1FoUTVQYVZpDWBQMF00ATAHYQUxUWFZI1oyCi4FOwAxVjgHMQIoVG8HdwdaCj4KaAQ0USVUbAEiASUMfAE9V3xWPwpsUGAEPlIuBzoIMVM2UX9RYVA3VmMNd1BgXTQBfwdhBW5RZVkjWjIKLgU7ADFWOAcxAihUcwd0B2AKLQpTBDFRMFRsAT8BIgx8AT1XfFY%2FCm5QbQQ%2BUi4HSghwU2BRMlE7UGBWfQ0RUCJddAEhBxMFO1E%2FWWRaZwopBS4ANFYmBz4CJFQ3BzQHJQp3CkYEMVEhVGgBfgFnDG8BKFc%2FVisKbFBnBC1SLgcwCHNTO1FgUWBQP1ZyDTVQN11zASUHDwU2UTVZdVpgCisFaAB0VnEHKQIxVG8HPQc0CmkKOgRnUW5UPgFlAWMMaQE2VzRWeA%3D%3D; expires=Wed, 09-Nov-2022 08:16:10 GMT; Max-Age=7200; path=/
Expires: Tue, 01 Jan 2000 00:00:00 GMT
Last-Modified: Wed, 09 Nov 2022 06:16:10 GMT
Cache-Control: no-store, no-cache, must-revalidate, max-age=0
Cache-Control: post-check=0, pre-check=0
Pragma: no-cache

{
    "status": false,
    "error": "You are already logged out. Please login again",
    "response_code": 400
}

解决思路及修复方案

1. 修正Content-Type请求头

你手动设置了Content-Type: application/json,但实际使用formParam传递表单数据,这会导致服务端无法正确解析请求参数,进而触发认证失败。

修复方式:

  • 直接删除手动设置的Content-Type,REST Assured在使用formParam时会自动设置正确的Content-Type: application/x-www-form-urlencoded
  • 或者手动将Content-Type改为application/x-www-form-urlencoded

修改后的header代码示例:

HashMap<String, String> header_params = new HashMap<>();
header_params.put("x-auth-token", getValueFromPropertyFile(PropertyFileKeys.X_AUTH_TOKEN));
// 移除错误的Content-Type设置,或替换为正确类型
// header_params.put("Content-Type", "application/x-www-form-urlencoded");

2. 验证Token有效性

检查两个Token的有效性:

  • 请求头中的x-auth-token:确认从配置文件读取的Token是否已过期或无效
  • Form参数中的token(即admin_login_token):确认该Token是最新的登录凭证,未过期

可以通过调用登录接口获取新Token,替换现有值后重新测试。

从响应的Set-Cookie字段可以看出,服务端依赖Session Cookie进行会话管理。当前请求未携带任何Cookie,可能导致服务端认为会话已失效。

修复方式:

  • 如果测试流程中先执行了登录接口,保存登录响应中的Cookie,并在后续请求中携带
  • 使用REST Assured的Cookie管理机制自动维护会话Cookie

示例代码(假设登录请求返回Cookie):

// 登录请求获取会话Cookie
Response loginResponse = given()
        .formParam("username", "admin")
        .formParam("password", "password")
        .post("/admin/login");

// 提取Session Cookie
String sessionCookie = loginResponse.getCookie("ITPLATPci_session");

// 在后续请求中携带该Cookie
request_specification = given()
        .spec(request_specification_builder)
        .cookie("ITPLATPci_session", sessionCookie)
        .formParam("id","1")
        // ... 其他form参数

4. 确认接口认证方式

联系开发团队或查看接口文档,确认该接口的认证规则:

  • 是否仅使用x-auth-token,还是需要同时携带Session Cookie
  • Form参数中的token是否为必填项,以及它的具体作用

内容的提问来源于stack exchange,提问作者Mangal Beriya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 23:50:37