Reserved CSRF protection with X-XSRF-TOKEN header (like angularjs)
I am trying to write a web integration test with spring verified authentication. The app uses AngularJS and spring Boot. Since I am using AngularJS, CSRF protection is done with the X-XSRF-TOKEN header and the XSRF-TOKEN cookie (as I understand its angular default).
How can I configure restassured to the generated one and submit this token using form authentication? Right now I have something like this:
given().auth().form("user", "password", new FormAuthConfig("login", "username", "password").sendCsrfTokenAsHeader()).when().get("/index.html").then().log().all().statusCode(200);
But in the logs I see that the CSRF token is invalid when submitting credentials to / login.
source to share
Some delay in response, but I hope this helps someone
Response loginResponse = given().contentType(APPLICATION_JSON).
param(USERNAME, "").
param(PASSWORD, "").
when().post(LOGIN_PROCESSING_URL).then().log().all().
extract().response();
given().contentType(APPLICATION_JSON).
cookie("XSRF-TOKEN", loginResponse.cookie("XSRF-TOKEN")).
header("X-XSRF-TOKEN", loginResponse.cookie("XSRF-TOKEN")).
sessionId(loginResponse.getSessionId()).
when().post(USER_PATH).
then().log().all().statusCode(CREATED.value());
source to share
You need to do 2 GET
before posting to use spring security CSRF protection in your rest client and test class.
- Make a request
GET
to login. This will return tokensJSESSIONID
and tokensXSRF-TOKEN
. If you use the returnedXSRF-TOKEN
toPOST
, it won't work because we got it with empty / falseJSESSIONID
. - Get useful
XSRF-TOKEN
from the secondGET
usingJSESSIONID
from the previous query. - Now you can use it
XSRF-TOKEN
for yoursPOST
.
An example of using CSRF protection with X-XSRF-TOKEN
rest order:
//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);
source to share