RestAssured oAuth2 http状态码401

时间:2015-03-19 21:15:53

标签: rest oauth-2.0 spring-security-oauth2 rest-assured

我正在尝试使用RestAssured库和Spring MVC REST oAuth2安全端点实现集成测试。

这是我的测试:

@Test
public void testCreateDecision() throws Exception {
    File createDecisionJsonFile = ResourceUtils.getFile(getClass().getResource("/json/decisions/create-decision.json"));

    // @formatter:off
    final String createDecisionRequest = FileUtils.readFileToString(createDecisionJsonFile)
            .replace("{{name}}", "Test decision name")
            .replace("{{description}}", "Test decision description");
    // @formatter:on

    String accessToken = getAccessToken("user", "user");

    // @formatter:off
    given()
        .auth()
        .oauth2(accessToken, OAuthSignature.HEADER)
        .body(createDecisionRequest)
        .contentType("application/json; charset=UTF-8")
    .when()
        .post(format("http://localhost:%d/api/v1.0/decisions/create", port))
    .then()
        .statusCode(200)
        .contentType(ContentType.JSON)
        .body("id", notNullValue())
        .body("createDate", notNullValue());
    // @formatter:on

}

accessToken有效但我不断获得401 http代码。 我的代码有什么问题?

3 个答案:

答案 0 :(得分:10)

我知道这是一篇旧帖子,但只是想记录下来以防其他人需要答案。 我能够使用以下格式实现:

首先检索令牌(在我的情况下,我没有存储用户令牌,jut在每次测试之前得到它们)

// we need to get the oauth token before we can perform the request
private void authenticateUser(String username, String password) {

    String response =
            given()
                .parameters("username", username, "password", password, 
                           "grant_type", "password", "scope", "read write", 
                           "client_id", "clientapp", "client_secret", "123456")
                .auth()
                .preemptive()
                .basic("clientapp","123456")
            .when()
                .post("/oauth/token")
                .asString();

    JsonPath jsonPath = new JsonPath(response);
    accessToken = jsonPath.getString("access_token");
}

他们在测试中使用了检索到的令牌:

@Test
public void testGetUserDefaultUserOwner() {


    authenticateUser(testData.user1.getLogin(), "1");

    User user = 
        given()
            .auth().oauth2(accessToken)
            .contentType(ContentType.JSON)
            .accept(ContentType.JSON)
        .expect()
            .log().all()
            .statusCode(HttpStatus.OK.value())
        .when()
            .get(USER_RESOURCE, testData.user1.getId())
            .as(User.class);

    assertThat(user).isEqualTo(testData.user1);
}   

我使用Restassured和AssertJ进行测试,使用带有OAuth2的SpringBoot进行Rest API。

答案 1 :(得分:1)

我已使用OAuth2RestTemplate重新实现了我的测试:

ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();

resourceDetails.setUsername("user");
resourceDetails.setPassword("user");
resourceDetails.setAccessTokenUri(format("http://localhost:%d/oauth/token", port));
resourceDetails.setClientId("clientapp");
resourceDetails.setClientSecret("123456");
resourceDetails.setGrantType("password");
resourceDetails.setScope(asList("read", "write"));

DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();

OAuth2RestTemplate auth2RestTemplate = new OAuth2RestTemplate(resourceDetails, clientContext);
auth2RestTemplate.setMessageConverters(asList(new MappingJackson2HttpMessageConverter()));

Assert.assertNotNull(auth2RestTemplate.getAccessToken());

DecisionRequest decisionRequest = new DecisionRequest(name, description, parentDecisionId);

auth2RestTemplate.postForObject(format("http://localhost:%d/api/v1.0/decisions/create", port), decisionRequest, Decision.class);

答案 2 :(得分:-2)

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>302 Found</title>
</head><body>
<h1>Found</h1>
<p>The document has moved <a href="https://example.com/404/index.html">here</a>.</p>
</body></html>