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

Rest Assured中如何通过Header传Token?排查403错误问题

排查403权限错误的解决方案

看了你的代码,我发现两个核心问题导致了403错误,咱们一步步修正:

1. Authorization请求头格式错误

你的代码里拼接Authorization头时,Bearer和token之间缺少了一个空格——这是OAuth2 Bearer令牌的标准格式要求。服务端无法解析错误格式的令牌,直接返回403。

错误写法:

.header("Authorization", "Bearer" + token)

正确写法:

.header("Authorization", "Bearer " + token) // Bearer后必须加空格

2. 未正确提取登录接口返回的Token

你的LoginEndpoint.createToken()方法直接返回了整个登录响应的字符串,但登录接口返回的是包含token字段的JSON(比如{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."})。直接传递整个JSON字符串作为令牌,服务端肯定无法识别。

修正LoginEndpoint,用JsonPath精准提取token字段的值:

public class LoginEndpoint {
    public String createToken(){
        AuthPojo authPayload = new AuthPojo("admin", "password");
        return given()
                .body(authPayload)
                .post("https://automationintesting.online/auth/login")
                .jsonPath().getString("token"); // 提取JSON中的token字段
    }
}

修正后的完整测试代码

@Test
public void givenCorrectRoomDataWhenPostRoomThenReturnListWithNewlyCreatedRoomTest() {
    LoginEndpoint loginEndpoint = new LoginEndpoint();
    RoomPojo roomPojo = new RoomPojo();
    String token = loginEndpoint.createToken();

    roomPojo.setAccessible(true);
    roomPojo.setType("Single");
    roomPojo.setDescription("The very first single room");
    roomPojo.setImage("https://i.pinimg.com/originals/51/23/f0/5123f08b6e9c4441f27abf07cfee09c9.jpg");
    roomPojo.setRoomId(12);
    roomPojo.setRoomPrice(94);
    // 注意:如果features是接口必填字段,记得补充设置,否则可能导致请求失败
    // roomPojo.setFeatures(Arrays.asList("WiFi", "TV"));
    roomPojo.setRoomNumber(22);

    given()
            .header("Authorization", "Bearer " + token)
            .body(roomPojo)
            .when().post("https://automationintesting.online/room/") // 确保URL完整,若未配置全局baseURI
            .then().statusCode(200);
}

额外排查建议

  • 确认RoomPojo的序列化是否正确:比如是否添加了Jackson的@JsonProperty注解,保证请求体的字段名和服务端要求一致(部分服务端会因请求体格式错误返回403而非400)。
  • 验证Token有效性:可以在代码中打印token值,用Postman手动调用房间接口,确认令牌本身能正常使用。
  • 检查请求URL:如果你的RestAssured没有全局配置baseURI,要确保post的URL是完整路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 18:22:38