Test a Session Login With CSRF in REST Assured
Test a browser-style login, covering reading a CSRF token from an HTML form with htmlPath(), keeping JSESSIONID across requests with a SessionFilter, setting the session id explicitly, and a missing or reused CSRF token.
The bank’s online portal doesn’t use tokens: customers log in with an HTML form, and a session cookie keeps them logged in. Your first test posts the user name and password straight to the login endpoint and gets 403, because the form also carries a hidden CSRF token. A second test follows every redirect, and passes while looking at the login page. In this guide, you’ll log in the way a browser does, keep the session across requests, and test the CSRF protection itself.
Level: Intermediate · Time: 20 minutes · Part of: Module 7: Authentication and Transport Security, section 4
What You’ll Build
You’ll build a test class called SessionAndCsrfTest with five tests and two helpers. The helpers read the CSRF token from the login page and post the form; the tests use the session, send the session id without a filter, check a request without a session, and prove that a missing or reused CSRF token is rejected.
The login helper posts the form and checks this response:
1
2
3
4
5
6
7
8
9
POST /portal/login HTTP/1.1
Host: localhost:<port>
Content-Type: application/x-www-form-urlencoded
_csrf=88928ffd-...&username=anna&password=correct%20horse
HTTP/1.1 302
Location: /portal/home
Set-Cookie: JSESSIONID=f7b2294d-3cdb-4fc7-95e0-758821ce8323; Path=/portal; HttpOnly; SameSite=Lax
When you’re done, Maven reports five passing tests:
1
2
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Log in through the form.
- Use the session.
- Check a request without a session.
- Test the CSRF protection.
What You Need
- About 20 minutes
- JDK 26 or later
- Maven 3.9 or later
- An IDE (IntelliJ IDEA, VS Code or Eclipse)
- Knowledge: you can send form parameters, as taught in Send Query and Form Parameters in REST Assured, read HTML with GPath, from Check XML and HTML Responses in REST Assured, and control redirects, from Configure Timeouts, Redirects and Charsets in REST Assured.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: create
SessionAndCsrfTestin a newsection_04package next to the classes from the previous sections, and follow every heading below. - Skip ahead: open the finished class (
SessionAndCsrfTest.java) and read along. You can run it at any time with the command in Run the Tests.
Get the code: if you haven’t cloned the examples repository yet, follow the steps in Test HTTP Basic Authentication in REST Assured.
Out of scope: this guide doesn’t cover testing a web application through a real browser; for pages with JavaScript, use a browser-testing tool.
Understand Sessions and CSRF Tokens
The problem. Online banking portals, admin consoles and many older web applications log users in with an HTML form, not a token. A test that posts credentials directly skips the form’s hidden fields, and a test that forgets the session cookie can’t get past the login. To test such an application, a test must behave like a browser: load the form, read the token, post the credentials, and send the session cookie with every request after that.
The concept. Two mechanisms are involved:
- A session is state the server keeps for a logged-in user. The server gives the browser a session id in a cookie, usually
JSESSIONID, and the browser sends it with every request. - A CSRF token protects against cross-site request forgery: a malicious page that makes the user’s browser post a form to the bank. The bank puts a random token in its own form and rejects posts without it. Another site can’t read the token, so it can’t forge the post.
REST Assured has two tools for this. SessionFilter remembers the session id from a response and sends it with every later request that uses the same filter. htmlPath() reads values from an HTML response, such as the CSRF token in a hidden input.
When to use it. Log in through the form, step by step, when the login itself is what you test, so you can check each step and the CSRF protection. Create a new SessionFilter for every test, so no test sees another test’s login. Keep login redirects visible, so you can see which step failed.
Log in like a browser, and test that the forged and replayed posts fail.
Meet the API Under Test
The bank’s portal has three endpoints:
| Request | Response |
|---|---|
GET /portal/login | An HTML login form with a hidden _csrf token |
POST /portal/login | 302 to /portal/home with a JSESSIONID cookie; 403 for a missing or reused CSRF token; 401 for wrong credentials |
GET /portal/home | {"user":"anna","message":"Welcome back"} with a valid session, or 302 to /portal/login |
The login form looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
<head>
<title>Sign in</title>
</head>
<body>
<form enctype="application/x-www-form-urlencoded" method="post" id="login" action="/portal/login">
<input type="hidden" name="_csrf" value="88928ffd-98ab-441d-a57a-992686c248ce"/>
<input type="text" name="username"/>
<input type="password" name="password"/>
<input type="submit" value="Sign in"/>
</form>
</body>
</html>
Each CSRF token can be used once. The user is anna with the password correct horse. A missing or reused token gets an RFC 9457 problem with the detail Missing or reused CSRF token, and a wrong password one with Wrong username or password.
Your tests check these values:
- The
_csrfvalue on the login page. - The status,
LocationandJSESSIONIDcookie of the login response. - The
useron the home page, and the status of every refused login.
Log In Through the Form
Set Up a Fresh Session per Test
Goal: create the test class with a new SessionFilter before every test.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.javanibble.module_07.section_04;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import com.javanibble.auth.BankAuthApi;
import io.restassured.filter.session.SessionFilter;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class SessionAndCsrfTest {
private static BankAuthApi api;
private SessionFilter session;
@BeforeAll
static void startApi() {
api = BankAuthApi.start();
}
@AfterAll
static void stopApi() {
api.close();
}
@BeforeEach
void newSession() {
session = new SessionFilter();
}
private RequestSpecification portal() {
return given().baseUri(api.baseUri()).port(api.port()).filter(session);
}
}
What’s happening:
sessionis an instance field, created before each test, so every test starts logged out.portal()adds the filter to every request, so all of a test’s requests share that test’s session.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Don’t make the
SessionFilterstatic. Every test would then share one session, and the result would depend on the order the tests run in. Create a filter per test, as@BeforeEachdoes here.
Read the CSRF Token
Goal: load the login page and read the hidden token.
Add this helper to SessionAndCsrfTest:
1
2
3
4
5
6
private String csrfTokenFromTheLoginPage() {
return portal()
.when().get("/portal/login")
.then().statusCode(200)
.extract().htmlPath().getString("**.find { it.@name == '_csrf' }.@value");
}
What’s happening:
extract().htmlPath()parses the page leniently, likeXmlPathon HTML in Module 3.**.find { it.@name == '_csrf' }finds the input by its name, wherever it is on the page, and.@valuereads its value.
Checkpoint: the class compiles. Nothing calls the helper yet.
Post the Form
Goal: post the token and the credentials, and check the redirect and the session cookie.
Add this helper to SessionAndCsrfTest:
1
2
3
4
5
6
7
8
9
10
11
12
private void logIn(String csrf) {
portal()
.formParam("_csrf", csrf)
.formParam("username", "anna")
.formParam("password", "correct horse")
.when()
.post("/portal/login")
.then()
.statusCode(302)
.header("Location", "/portal/home")
.cookie("JSESSIONID", notNullValue());
}
What’s happening:
- The form carries the CSRF token as well as the credentials, as the browser’s post would.
- REST Assured doesn’t follow a
POSTredirect by default, which is useful here: the test can check the redirect target and the new session cookie. - The
SessionFiltersees theJSESSIONIDcookie in the response and remembers it.
Checkpoint: the class compiles. The next step uses both helpers.
Use the Session
Open the Home Page
Goal: log in, and prove that the next request is logged in too.
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void logInAndUseTheSession() {
logIn(csrfTokenFromTheLoginPage());
assertNotNull(session.getSessionId());
portal()
.when()
.get("/portal/home")
.then()
.statusCode(200)
.body("user", equalTo("anna"));
}
What’s happening:
session.getSessionId()returns the id the filter remembered from the login.- The request to
/portal/homecarries no cookie in the test code, but the filter addsJSESSIONID, so the portal knows the user.
Checkpoint: run SessionAndCsrfTest from your IDE. One test runs and passes.
Send the Session Id Without a Filter
Goal: reuse the session id in a request that has no filter.
1
2
3
4
5
6
7
8
9
10
11
@Test
void theSessionIdCanBeSetExplicitly() {
logIn(csrfTokenFromTheLoginPage());
given().baseUri(api.baseUri()).port(api.port())
.sessionId(session.getSessionId())
.when()
.get("/portal/home")
.then()
.body("user", equalTo("anna"));
}
What’s happening:
sessionId(..)sendsJSESSIONID=<id>without a filter.- That’s useful when the session id comes from somewhere else, such as a login done once for a whole class.
Checkpoint: run the class again. Two tests pass.
SessionFilterandsessionId(..)use the cookie nameJSESSIONIDby default. For an application with another name, set it withSessionConfig.
Check a Request Without a Session
Keep the Login Redirect Visible
Goal: prove that a request without a session is sent to the login page.
1
2
3
4
5
6
7
8
9
10
@Test
void withoutASessionYouAreSentToTheLoginPage() {
given().baseUri(api.baseUri()).port(api.port())
.redirects().follow(false)
.when()
.get("/portal/home")
.then()
.statusCode(302)
.header("Location", "/portal/login");
}
What’s happening:
- The request has no session filter and no session id.
redirects().follow(false)keeps the302and itsLocationvisible.
Checkpoint: run the class again. Three tests pass.
Don’t follow a login redirect in a test about logging in. Followed, this request lands on the login page with
200 text/html, which looks like success and hides what really happened. Check the302and itsLocationinstead.
Test the CSRF Protection
Post Without a CSRF Token
Goal: prove that the right credentials alone don’t log in.
1
2
3
4
5
6
7
8
9
10
@Test
void aMissingCsrfTokenIsRejected() {
portal()
.formParam("username", "anna")
.formParam("password", "correct horse")
.when()
.post("/portal/login")
.then()
.statusCode(403);
}
What’s happening:
- The credentials are right, but the post doesn’t prove it came from the bank’s own form.
- The portal answers
403withMissing or reused CSRF token. This is the403from the opening.
Checkpoint: run the class again. Four tests pass.
Reuse a CSRF Token
Goal: prove that a token can’t be replayed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void aCsrfTokenWorksOnlyOnce() {
String csrf = csrfTokenFromTheLoginPage();
logIn(csrf);
portal()
.formParam("_csrf", csrf)
.formParam("username", "anna")
.formParam("password", "correct horse")
.when()
.post("/portal/login")
.then()
.statusCode(403);
}
What’s happening:
- The first login uses the token, so the second post with the same token is refused.
- A token that could be reused could be replayed by whoever captured it.
Checkpoint: run the class again. All five tests pass.
A login that works without a CSRF token, or with a used one, is a vulnerability, and no successful-login test notices it. Test the missing and the reused token, as these two tests do.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-07 -Dtest=SessionAndCsrfTest
You should see a result similar to the following:
1
2
3
4
5
6
[INFO] Running com.javanibble.module_07.section_04.SessionAndCsrfTest
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.603 s -- in com.javanibble.module_07.section_04.SessionAndCsrfTest
[INFO]
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Make a Test Fail
In portal(), remove .filter(session) and run the command again. You should see a result similar to the following:
1
2
3
4
[ERROR] Failures:
[ERROR] SessionAndCsrfTest.logInAndUseTheSession:74 expected: not <null>
[ERROR] Errors:
[ERROR] SessionAndCsrfTest.theSessionIdCanBeSetExplicitly:100 » IllegalArgument Session id value cannot be null
The login still succeeds, but without the filter nothing remembers the JSESSIONID cookie, so getSessionId() returns null. The first test fails on its assertNotNull(..), before it even reaches the home page, and the second fails when it tries to send a null session id. Both point at the missing session, not at the portal.
Put .filter(session) back and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
403 with Missing or reused CSRF token on a login | The post has no _csrf, or a token that was already used | Read a new token from the login page before each login |
401 with Wrong username or password | The credentials are wrong | Check the user name and password |
getSessionId() returns null | The requests don’t share a SessionFilter | Add .filter(session) to every request of the test |
| A login test passes while looking at the login page | A redirect was followed | Use redirects().follow(false), and check the 302 |
Try It Yourself
Exercise 1: Log In With the Wrong Password
Add a test called aWrongPasswordIsRefused that reads a CSRF token, posts the form with the password "wrong", and checks that the portal answers 401 with a detail that says the user name or password is wrong, and that no session id was stored.
Hint
Post the form as logIn(..) does, but with your own password, and check the status and detail in the chain. Then check session.getSessionId() with assertNull(..).
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void aWrongPasswordIsRefused() {
portal()
.formParam("_csrf", csrfTokenFromTheLoginPage())
.formParam("username", "anna")
.formParam("password", "wrong")
.when()
.post("/portal/login")
.then()
.statusCode(401)
.body("detail", equalTo("Wrong username or password"));
assertNull(session.getSessionId());
}
Add import static org.junit.jupiter.api.Assertions.assertNull; to the class.
Exercise 2: Check the Session Cookie and Its Isolation
Add a test called theSessionCookieIsLockedDownAndPrivate. Log in, checking with detailedCookie() that JSESSIONID has the path /portal, is HTTP-only, has SameSite=Lax, and holds a UUID. Then prove that the session is private: a request with a new SessionFilter is sent to the login page, while a request with the test’s own filter reaches the home page.
Hint
Write the login inline instead of calling logIn(..), so you can add the cookie check, as in Check Session Cookie Security in REST Assured. Remember redirects().follow(false) for the request with the new filter.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@Test
void theSessionCookieIsLockedDownAndPrivate() {
portal()
.formParam("_csrf", csrfTokenFromTheLoginPage())
.formParam("username", "anna")
.formParam("password", "correct horse")
.when()
.post("/portal/login")
.then()
.statusCode(302)
.cookie("JSESSIONID", detailedCookie()
.path("/portal")
.httpOnly(true)
.sameSite("Lax")
.value(matchesPattern("[0-9a-f-]{36}")));
given().baseUri(api.baseUri()).port(api.port())
.filter(new SessionFilter())
.redirects().follow(false)
.when()
.get("/portal/home")
.then()
.statusCode(302)
.header("Location", "/portal/login");
portal().when().get("/portal/home").then().statusCode(200).body("user", equalTo("anna"));
}
Add static imports for RestAssuredMatchers.detailedCookie and Matchers.matchesPattern to the class.
Summary
You built SessionAndCsrfTest, which logs in through the portal’s form with its CSRF token, keeps the session across requests, sends the session id without a filter, checks a request without a session, and proves that a missing or reused CSRF token is refused. The login test now posts what a browser posts, and sees every step.
- A browser-style login needs three steps: read the CSRF token from the form with
htmlPath(), post the form with the token and the credentials, and keep the session cookie for the requests after that. - A
SessionFilter, created per test, remembersJSESSIONIDand sends it automatically. sessionId(..)sends a session id without a filter.- Keep login redirects visible with
redirects().follow(false), so you can see which step failed. - Test what must fail too: no session, a missing CSRF token and a reused one.
Here are the commands you used in this guide:
1
mvn test -pl module-07 -Dtest=SessionAndCsrfTest
What’s Next
Next: continue with Test HTTPS and Mutual TLS in REST Assured, which calls an API over HTTPS with a trust store, and with a client certificate.
The code:
- The finished test class:
SessionAndCsrfTest.java - The code and run commands for this module: Module 7 README
Go deeper:
- OWASP Cross-Site Request Forgery Prevention Cheat Sheet, for how CSRF tokens protect a form.
- OWASP Session Management Cheat Sheet, for the attributes a session cookie needs.
- REST Assured Usage wiki, for
SessionFilter, session ids and form authentication.
Related guides:
- Check Session Cookie Security in REST Assured, for checking a session cookie’s attributes.
- Write Negative Security Tests for OAuth 2.0 in REST Assured, for testing what token-based APIs must refuse.
