X-XSRF Token in the header
XSRF-TOKEN and JSESSIONID in the cookie
当我点击登录的get方法时,不会生成页面sessionID,我需要将其放置在JSESSIONID cookie中
登录/身份验证API被调用两次(我正在使用表单身份验证)
公共类登录{
SessionFilter sessionFilter = new SessionFilter();
private class SessionData
{
private String csrf;
private String session;
public SessionData(String header, String sessionId){this.csrf = header;this.session = sessionId;}
public String getCsrf(){return csrf;}
public String getSessionId(){return session;}
}
protected SessionData login(String username, String password) {
Response getLoginPage =
given().log().all().
filter(sessionFilter).
when().
get("/").
then().log().all().
extract().response();
String loginPage_csrf = getLoginPage.getCookies().get("XSRF-TOKEN");
System.out.println("1st response end get login page :" + loginPage_csrf );
Response login_cred =
given().log().all().
auth().form(username,password,new FormAuthConfig("/api/authentication", "j_username", "j_password").withLoggingEnabled()).
header("X-XSRF-TOKEN",loginPage_csrf).
filter(sessionFilter).
when().
post("/api/authentication").
then().log().all().
extract().response();
String Loggedin_csrf = login_cred.getCookies().get("XSRF-TOKEN");
System.out.println("2nd response authentication :" + Loggedin_csrf );
return new SessionData(Loggedin_csrf, sessionFilter.getSessionId());
}
@Test
public void create_role() throws IOException
{
RestAssured.baseURI = "https://apitest.com";
SessionData sessionData = login("admin", "admin");
final Response response =
(Response) given().log().all().
contentType("application/json; charset=UTF-16").
header("X-XSRF-TOKEN", sessionData.getCsrf()).
filter(sessionFilter).
body(getString("JSON Files/Roles_Section/CreateRole.JSON")).
when().
post("/api/authority").then().log().all();
response.body().prettyPrint();
Assert.assertEquals(response.getStatusCode(),HttpStatus.SC_ACCEPTED);
}
// read Payload from JSON file
public String getString(String path) throws IOException {return new String(Files.readAllBytes(Paths.get(path)));}
}