CSRF and session boundaries
What you will learn
Browser sessions create ambient credentials. Protect state-changing requests with CSRF tokens and distinguish cross-origin policy from access control.
- Explain session fixation and CSRF defenses.
- Distinguish CORS from authentication and CSRF.
- Design positive and negative browser-session tests.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Spring Security examples require the separate pinned companion Maven project. Their predicted results are not execution evidence.
CSRF decision model
public class Main { static boolean permit(String method,boolean validToken){return java.util.Set.of("GET","HEAD","OPTIONS","TRACE").contains(method)||validToken;} public static void main(String[] args) {for(boolean token:new boolean[]{false,true})System.out.println(permit("POST",token));System.out.println(permit("GET",false)); }}Expected output:
falsetruetrueThis model assumes authenticated browser access and a token already checked by a framework; it does not generate tokens or implement CSRF protection.
Sessions and CSRF
A browser automatically sends matching cookies, so another origin can sometimes trigger a request with the victim’s credentials. CSRF defenses require an unpredictable token bound to the expected session or approved token repository for state-changing requests. Spring Security enables CSRF by default and generally exempts safe methods GET, HEAD, OPTIONS and TRACE; GET must not mutate state. Token transport depends on the client and repository; the server must validate it. SameSite cookies reduce exposure but are not a complete substitute. Use HTTPS, Secure and HttpOnly session cookies as appropriate, sensible expiration and fixation protection (session ID change on login by default in modern Servlet containers). Logout with CSRF enabled normally requires POST with a valid token; default handlers invalidate the session and clear security context. Invalidate server-side state, not just the page. Stateless bearer-only APIs can have a different threat model if no automatically attached credential is accepted; do not disable CSRF simply because an endpoint returns JSON. The lab leaves it enabled in both chains.
Cross-origin requests
CORS controls which browser origins may read or send particular cross-origin requests under browser rules; it does not grant identity or object access and is not a general CSRF defense. A preflight OPTIONS request may omit authentication cookies, so CORS processing must precede security authentication. Configure explicit trusted origins, methods and headers; credentials require appropriate explicit origins. The lab permits a fictional origin, GET and Authorization header, with credentials disallowed. Non-browser clients are not governed by browser CORS enforcement. Do not use a permissive wildcard as a cure for a 403. For protected browser POSTs, test no token, invalid token, valid token without role, valid token with role, actual login and logout. All such Spring tests are supplied but not executed.
CORS origin and method policy
public class Main { static boolean cors(String origin,String method){return "https://ui.example.invalid".equals(origin)&&"GET".equals(method);} public static void main(String[] args) {System.out.println(cors("https://ui.example.invalid","GET"));System.out.println(cors("https://other.example.invalid","GET"));System.out.println(cors("https://ui.example.invalid","POST")); }}Expected output:
truefalsefalseThis is an allowlist model only; an accepted origin does not authenticate the user.
Browser security and password encoder
Source-reviewed, NOT RUN. File lab-fixtures/spring-security-v41/src/main/java/example/tenant/BrowserSecurity.java; use the companion lab README.
package example.tenant;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.annotation.Order;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.core.userdetails.User;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.crypto.factory.PasswordEncoderFactories;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.security.provisioning.InMemoryUserDetailsManager;import org.springframework.security.web.SecurityFilterChain;@Configurationpublic class BrowserSecurity { @Bean @Order(2) SecurityFilterChain browser(HttpSecurity http) throws Exception { return http.authorizeHttpRequests(a -> a .requestMatchers("/browser/**").hasRole("READER") .anyRequest().denyAll()) .formLogin(f -> f.permitAll().defaultSuccessUrl("/browser/home",true)) .logout(l -> l.logoutSuccessUrl("/login?logout").permitAll()) .build(); // CSRF remains enabled; POST logout requires its token. } @Bean PasswordEncoder encoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); } @Bean UserDetailsService users(PasswordEncoder encoder, @Value("${lab.browser-password}") String password) { if (password.isBlank()) throw new IllegalArgumentException("Missing lab password"); return new InMemoryUserDetailsManager(User.withUsername("lab-reader") .password(encoder.encode(password)).roles("READER").build()); }}Predicted behavior: Form login, READER authority, CSRF enabled, logout and adaptive password encoder.
A catch-all chain denies unrelated routes; the synthetic test user is not for deployment.
Browser negative and positive tests
Source-reviewed, NOT RUN. File lab-fixtures/spring-security-v41/src/test/java/example/tenant/BrowserSecurityTest.java; use the companion lab README.
package example.tenant;import org.junit.jupiter.api.*;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.bean.override.mockito.MockitoBean;import org.springframework.security.oauth2.jwt.JwtDecoder;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.setup.MockMvcBuilders;import org.springframework.web.context.WebApplicationContext;import static org.junit.jupiter.api.Assertions.*;import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;@SpringBootTest(properties="lab.browser-password=synthetic-test-only")class BrowserSecurityTest { @Autowired WebApplicationContext context; @Autowired PasswordEncoder encoder; @MockitoBean JwtDecoder decoder; MockMvc mvc; @BeforeEach void setup() { mvc=MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); } @Test void csrfRequired() throws Exception { mvc.perform(post("/browser/note").with(user("reader").roles("READER"))) .andExpect(status().isForbidden()); mvc.perform(post("/browser/note").with(user("reader").roles("READER")).with(csrf())) .andExpect(status().isOk()); mvc.perform(post("/browser/note").with(user("reader").roles("READER")).with(csrf().useInvalidToken())) .andExpect(status().isForbidden()); } @Test void roleRequired() throws Exception { mvc.perform(post("/browser/note").with(user("reader").roles("OTHER")).with(csrf())) .andExpect(status().isForbidden()); } @Test void passwordEncoder() { String encoded=encoder.encode("synthetic-only"); assertTrue(encoder.matches("synthetic-only",encoded)); assertFalse(encoder.matches("different",encoded)); } @Test void loginThenLogout() throws Exception { var login=mvc.perform(post("/login").param("username","lab-reader") .param("password","synthetic-test-only").with(csrf())) .andExpect(status().is3xxRedirection()).andExpect(redirectedUrl("/browser/home")).andReturn(); var session=(org.springframework.mock.web.MockHttpSession)login.getRequest().getSession(false); assertNotNull(session); mvc.perform(get("/browser/home").session(session)).andExpect(status().isOk()); mvc.perform(post("/logout").session(session).with(csrf())) .andExpect(status().is3xxRedirection()); assertTrue(session.isInvalid()); }}Predicted behavior: CSRF failures return 403; valid reader POST succeeds; login and logout manage the test session.
MockMvc tests also exercise encoder matching; all require actual Spring execution.
Common mistakes
Do not change data on GET, confuse CORS with CSRF, permit all origins to solve an authorization failure, disable CSRF globally, or assume logout revokes access tokens issued elsewhere.
Practice
Model a browser POST that requires authentication, READER authority and a validated CSRF token. Print false for each missing prerequisite and true only when all are present.
Expected output:
falsefalsefalsetrueCompare with the manual review criteria.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
CSRF and session boundaries — knowledge check
Spring Security identity and authorization reasoning.
Why can a browser session be vulnerable to CSRF?
Should GET modify state?
What does CORS control?
Why process preflight before authentication?
What should session logout do?