使用CSRF进行集成测试,确保安全和基本认证

时间:2016-01-08 07:52:59

标签: spring-security spring-boot csrf rest-assured

我有一个基于https://spring.io/guides/tutorials/spring-security-and-angular-js/

的AngularJs应用程序的Spring Boot

我正在使用基本身份验证,我想为它编写集成测试。目前,我总是收到403状态代码,其中包含以下消息:

Expected CSRF token not found. Has your session expired?

这是我的测试:

@Test
public void givenAdmin_deleteOfBookIsAllowed() {

    Response response = given().auth().preemptive().basic("admin", "admin").get("/api/user/");
    response.then().log().all();
    String sessionId = response.sessionId();
    String token = response.cookie("XSRF-TOKEN");

    Book book = Books.randomBook();
    bookRepository.save(book);

    given()
            .sessionId(sessionId)
            .cookie("XSRF-TOKEN", token)
            .header("X-XSRF-TOKEN", token)
            .pathParam("id", book.getId().getId())
            .when().delete("/api/books/{id}")
            .then().statusCode(HttpStatus.SC_NO_CONTENT);
}

我根据教程使用自定义令牌库:

 private CsrfTokenRepository csrfTokenRepository() {
    HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
    repository.setHeaderName("X-XSRF-TOKEN");
    return repository;
}

这是第一次通话的请求/回复:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Set-Cookie: JSESSIONID=7020E58A8D6DC2C883FD5D6BD086512A; Path=/; HttpOnly
Set-Cookie: XSRF-TOKEN=6c44ae09-73f9-4115-bbbf-b01773ec1b91; Path=/
X-Application-Context: application:staging:0
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Content-Encoding: gzip
Vary: Accept-Encoding
Date: Fri, 08 Jan 2016 07:43:21 GMT

{
    "details": {
        "remoteAddress": "127.0.0.1",
        "sessionId": "7020E58A8D6DC2C883FD5D6BD086512A"
    },
    "authorities": [
        {
            "authority": "ROLE_ADMIN"
        },
        {
            "authority": "ROLE_USER"
        }
    ],
    "authenticated": true,
    "principal": {
        "password": null,
        "username": "admin",
        "authorities": [
            {
                "authority": "ROLE_ADMIN"
            },
            {
                "authority": "ROLE_USER"
            }
        ],
        "accountNonExpired": true,
        "accountNonLocked": true,
        "credentialsNonExpired": true,
        "enabled": true
    },
    "credentials": null,
    "name": "admin"
}

从第二个电话:

Request method: DELETE
Request path:   http://localhost:64588/api/books/04ad6d12-9b59-4ade-9a8a-e45daccb1f61
Proxy:          <none>
Request params: <none>
Query params:   <none>
Form params:    <none>
Path params:    id=04ad6d12-9b59-4ade-9a8a-e45daccb1f61
Multiparts:     <none>
Headers:        X-XSRF-TOKEN=6c44ae09-73f9-4115-bbbf-b01773ec1b91
                Accept=*/*
Cookies:        JSESSIONID=7020E58A8D6DC2C883FD5D6BD086512A
                XSRF-TOKEN=6c44ae09-73f9-4115-bbbf-b01773ec1b91
Body:           <none>

HTTP/1.1 403 Forbidden
Server: Apache-Coyote/1.1
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Content-Encoding: gzip
Vary: Accept-Encoding
Date: Fri, 08 Jan 2016 07:44:21 GMT

{
    "timestamp": "2016-01-08T07:44:21.963+0000",
    "status": 403,
    "error": "Forbidden",
    "message": "Expected CSRF token not found. Has your session expired?",
    "path": "/api/books/04ad6d12-9b59-4ade-9a8a-e45daccb1f61"
}

1 个答案:

答案 0 :(得分:3)

您需要在发布之前执行2 undefined以在您的休息客户端或集成测试中使用spring security GET保护。

  1. 发出CSRF个登录请求。这将返回GET令牌和JSESSIONID令牌。如果您使用返回的XSRF-TOKENXSRF-TOKEN,则会失败,因为我们使用空/假POST来获取它。
  2. 使用先前请求中的JSESSIONID从第二个XSRF-TOKEN获取有用的GET
  3. 现在,您可以JSESSIONID使用XSRF-TOKEN
  4. 使用基本身份验证和POST保护确保的示例集成测试:

    CSRF