JWT Login and Cookies with Selection and Iteration
Unit 2 · Lesson 2.1 · 5 minutes
This lesson uses a JWT stored in an authentication cookie to practice two Unit 2 control structures: iteration searches the request's cookies, and selection decides whether the request is allowed or rejected.
Learning Objective and Success Criteria
if statements to select the correct authentication resultAuthentication introduces several unfamiliar terms at once. You do not need to implement cryptography in this lesson. Treat signatureValid and expired as results already produced by the server’s JWT library, then focus on how the Java control flow uses those results.
Trace the Login Data
After a successful login, a server can send a signed JWT in a cookie:
Set-Cookie: auth_token=<signed-jwt>; HttpOnly; Secure; SameSite=Lax
On a later request, the browser sends that cookie back. The server must locate auth_token, verify the JWT signature, and check its expiration before allowing access. In this teaching model, the web framework has already separated the incoming cookie header into a String[].
| Input | Processing | Output |
|---|---|---|
| Request cookies | Iterate until auth_token is found |
JWT text or null |
| JWT validation results | Select the first matching rejection condition | 401 or 200 response |
Read the Java Algorithm
Read findAuthToken first. Its enhanced for loop checks each cookie and stops early with return when the authentication cookie is found. Then read authorize: its ordered if statements ensure that a missing, invalid, or expired JWT cannot reach the success response.
Code Runner Challenge
Run the request checks, then change one input and predict the new result.
View IPYNB Source
// CODE_RUNNER: Run the request checks, then change one input and predict the new result.
public class JwtCookieFlow {
public static String findAuthToken(String[] cookies) {
for (String cookie : cookies) {
if (cookie.startsWith("auth_token=")) {
return cookie.substring("auth_token=".length());
}
}
return null;
}
public static String authorize(
String[] cookies, boolean signatureValid, boolean expired) {
String jwt = findAuthToken(cookies);
if (jwt == null) {
return "401: missing authentication cookie";
}
if (!signatureValid) {
return "401: invalid JWT signature";
}
if (expired) {
return "401: expired JWT";
}
return "200: request allowed";
}
public static void main(String[] args) {
String[] validCookies = {"theme=dark", "auth_token=abc.def.sig"};
String[] missingCookies = {"theme=dark", "language=en"};
System.out.println(authorize(validCookies, true, false));
System.out.println(authorize(missingCookies, true, false));
System.out.println(authorize(validCookies, false, false));
System.out.println(authorize(validCookies, true, true));
}
}
JwtCookieFlow.main(null);
Popcorn Check
If auth_token is the second cookie, how many loop iterations occur?
Two. The first cookie fails the startsWith condition. The second passes, so the method returns immediately and the loop ends.
Why is the missing-cookie check performed before signature validation?
There is no JWT to validate when the cookie search returns null. The first selection handles that input before later checks use the token.
Security boundary: this code models control flow, not production JWT verification. A real server should use a maintained JWT library, verify the expected signing algorithm and claims, use HTTPS, and avoid printing credentials or token contents.
Homework Hacks
Three hacks · 5 minutes each
Each starter compiles before you edit it, so you can run the initial version and compare its incorrect output with the expected output. Change only the requested method.
Homework Hack 1 — Select a JWT Result (5 minutes)
selection Complete validateJwt. Return "invalid signature" when the signature is invalid, "expired" when the token is expired, and "valid" otherwise. Keep the checks in that order.
Code Runner Challenge
Add ordered if statements so all three checks print true.
View IPYNB Source
// CODE_RUNNER: Add ordered if statements so all three checks print true.
public class JwtSelectionHack {
public static String validateJwt(boolean signatureValid, boolean expired) {
// TODO: use selection to return the required result.
return "not implemented";
}
public static void main(String[] args) {
System.out.println(validateJwt(false, false).equals("invalid signature"));
System.out.println(validateJwt(true, true).equals("expired"));
System.out.println(validateJwt(true, false).equals("valid"));
}
}
JwtSelectionHack.main(null);
Homework Hack 2 — Find the Authentication Cookie (5 minutes)
iteration Complete findAuthCookie. Iterate through cookies, return the complete string that begins with "auth_token=", and return null after the loop when no match exists.
Code Runner Challenge
Add a loop so both provided checks print true.
View IPYNB Source
// CODE_RUNNER: Add a loop so both provided checks print true.
public class CookieIterationHack {
public static String findAuthCookie(String[] cookies) {
// TODO: iterate through the array and return the matching cookie.
return null;
}
public static void main(String[] args) {
String[] present = {"theme=dark", "auth_token=abc.def.sig"};
String[] missing = {"theme=dark", "language=en"};
System.out.println("auth_token=abc.def.sig".equals(findAuthCookie(present)));
System.out.println(findAuthCookie(missing) == null);
}
}
CookieIterationHack.main(null);
Homework Hack 3 — Combine Iteration and Selection (5 minutes)
combined algorithm Complete isAuthorized. Iterate to determine whether an auth_token cookie exists, then return true only when the cookie exists, the signature is valid, and the JWT is not expired.
Code Runner Challenge
Combine a cookie-search loop with a compound Boolean result.
View IPYNB Source
// CODE_RUNNER: Combine a cookie-search loop with a compound Boolean result.
public class AuthAlgorithmHack {
public static boolean isAuthorized(
String[] cookies, boolean signatureValid, boolean expired) {
boolean authCookiePresent = false;
// TODO: iterate through cookies and update authCookiePresent.
// TODO: combine all three authorization conditions.
return false;
}
public static void main(String[] args) {
String[] present = {"theme=dark", "auth_token=abc.def.sig"};
String[] missing = {"theme=dark"};
System.out.println(isAuthorized(present, true, false));
System.out.println(!isAuthorized(missing, true, false));
System.out.println(!isAuthorized(present, false, false));
System.out.println(!isAuthorized(present, true, true));
}
}
AuthAlgorithmHack.main(null);
Submission Checklist and Grading
The three hacks are worth 1 point total.
- 0.3 — Hack 1: ordered selection returns all three required JWT results
- 0.3 — Hack 2: iteration finds the authentication cookie and handles no match
- 0.4 — Hack 3: iteration and Boolean selection correctly authorize all four tests
Before submitting, run each homework cell and confirm every printed check is true. Do not include a real password, session cookie, or JWT in your work.
Lesson Design and Revision
Learner need: Authentication terminology can hide the Unit 2 control structures students are meant to practice.
Feedback applied: Avoid unrelated analogies and explain the concept through code.
Revision made: The lesson traces one request through a real cookie-search loop and ordered if statements. Each homework starter compiles before editing, allowing students to run it, observe the incorrect checks, and improve one method at a time.
References
- College Board. (2025). AP Computer Science A course and exam description: Unit 2, Selection and Iteration. https://apcentral.collegeboard.org/media/pdf/ap-computer-science-a-course-and-exam-description.pdf
- Jones, M., Bradley, J., & Sakimura, N. (2015). JSON Web Token (JWT) (RFC 7519). Internet Engineering Task Force. https://www.rfc-editor.org/rfc/rfc7519
- Mozilla. (n.d.). Set-Cookie header. MDN Web Docs. https://developer.mozilla.org/docs/Web/HTTP/Reference/Headers/Set-Cookie
Submit Assignment
Need to update a submission later? Open the submissions dashboard.