使用X-XSRF-TOKEN(如angularjs)标头重新确保CSRF保护

前端之家收集整理的这篇文章主要介绍了使用X-XSRF-TOKEN(如angularjs)标头重新确保CSRF保护前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用重新安全的 Spring安全身份验证编写Web集成测试.该应用程序使用AngularJS和Spring Boot.
由于我使用AngularJS,CSRF保护是通过X-XSRF-TOKEN标头和XSRF-TOKEN cookie完成的(据我所知,它的默认值为angular).

如何配置restassured生成并使用表单身份验证发送此令牌?现在我有这样的事情:

given().auth().form("user","password",new FormAuthConfig("login","username","password").sendCsrfTokenAsHeader()).when().get("/index.html").then().log().all().statusCode(200);

但是在日志中,我发现在将凭据发布到/ login时,CSRF令牌无效.

解决方法

您需要在发布之前进行2次GET,以便在您的其他客户端和测试类中使用spring security CSRF保护.

>发出GET请求登录.这将返回JSESSIONID标记和XSRF-TOKEN标记.如果你使用返回的XSRF-TOKEN进行POST,它将失败,因为我们使用空/假JSESSIONID.
>使用先前请求中的JSESSIONID从第二个GET获取有用的XSRF-TOKEN.
>现在您可以使用XSRF-TOKEN进行POST.

示例如何在放心使用X-XSRF-TOKEN时使用CSRF保护:

//1) get sessionId
Response response =
        given().auth().preemptive().basic(userName,userPassword).contentType(JSON).
        when().get(PREFIX_URL + "/users/user").
        then().log().all().extract().response();
String jsessionidId =  response.getSessionId();//or response.cookie("JSESSIONID");

//2) get XSRF-TOKEN using new/real sessionId
response =
        given().
        sessionId(jsessionidId).//or cookie("JSESSIONID",jsessionidId).
        contentType(JSON).
        when().get(PREFIX_URL + "/users/user").
        then().log().all().extract().response();

//3) post data using XSRF-TOKEN
given().log().all().
        sessionId(jsessionidId).//or cookie("JSESSIONID",jsessionidId).
        header("X-XSRF-TOKEN",response.cookie("XSRF-TOKEN")).
        queryParam("pos",pos.getId()).
        queryParam("date",date).
        queryParam("group_id",itemGroup.getId()).
        body(orderItems).
        contentType(JSON).
when().
        post(PREFIX_URL + "/orders/orderitems").
then().
    log().all().assertThat().statusCode(200);

猜你在找的Angularjs相关文章