Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 39 ยท Projects and Practice

Project: A Role-Based Admin Console with Sessions

Plan a server-rendered admin console: form login, roles and a role hierarchy, session fixation protection, CSRF tokens and audit trail, with a runnable Java stand-in of the rules.

The first project was a stateless token API. This one is the opposite: a classic server-rendered application with form login, a session cookie, roles for staff and admins, and CSRF protection on every state-changing form. Browser apps like this are where Spring Security's defaults help the most, so the project is mostly about not turning them off.

Spring Security cannot run on this site. The real configuration is read-only; the runnable program models the key behaviours (role hierarchy, session id rotation at login, CSRF token check) in plain Java so you can try the logic.

Requirements

Page or action Who
/login, /css/** Everyone
/dashboard Any signed-in staff member
/users (list) SUPPORT and above
POST /users/{id}/disable ADMIN only, with a valid CSRF token
/audit AUDITOR or ADMIN

Roles form a hierarchy: ADMIN includes SUPPORT, and SUPPORT includes STAFF, so you declare each rule once instead of listing every role.

The configuration (read-only)

Java
@Configuration
@EnableMethodSecurity
class WebSecurityConfig {

    @Bean
    SecurityFilterChain web(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/login", "/css/**").permitAll()
                .requestMatchers("/audit").hasAnyRole("AUDITOR", "ADMIN")
                .requestMatchers(HttpMethod.POST, "/users/**").hasRole("ADMIN")
                .requestMatchers("/users/**").hasRole("SUPPORT")
                .anyRequest().hasRole("STAFF"))
            .formLogin(form -> form.loginPage("/login").defaultSuccessUrl("/dashboard", true))
            .logout(logout -> logout.logoutSuccessUrl("/login?bye"))
            .sessionManagement(s -> s.maximumSessions(2).maxSessionsPreventsLogin(false))
            .headers(h -> h.contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'self'")));
        return http.build();
    }

    @Bean
    RoleHierarchy roleHierarchy() {
        return RoleHierarchyImpl.fromHierarchy("""
            ROLE_ADMIN > ROLE_SUPPORT
            ROLE_SUPPORT > ROLE_STAFF
            """);
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}

CSRF is not configured because the default is correct for browser forms. Thymeleaf adds the hidden token to every th:action form automatically; in other templates you add it yourself:

HTML
<form method="post" action="/users/7/disable">
  <input type="hidden" name="_csrf" value="${_csrf.token}">
  <button>Disable user</button>
</form>

Browser app defaults

Session cookie HttpOnly, Secure, SameSite
CSRF token On every POST form
New session id Changed at login
Logout Invalidate and clear

Keep these on; they are the point

1 / 2

The rules in plain Java (stand-in)

The program below resolves the hierarchy, rotates the session id at login (the defence against session fixation), and rejects a POST without the right CSRF token. Compare its output with what you expect from the table above.

Java Roles, session rotation and CSRF (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The planted session id does not survive login, a support user can read the user list but not disable accounts, and an admin still needs the CSRF token. Those are exactly the three guarantees Spring's defaults provide.

Testing the real thing

Java
@Test
@WithMockUser(roles = "SUPPORT")
void supportCannotDisableUsers() throws Exception {
    mvc.perform(post("/users/7/disable").with(csrf()))
        .andExpect(status().isForbidden());
}

@Test
@WithMockUser(roles = "ADMIN")
void adminNeedsCsrfToken() throws Exception {
    mvc.perform(post("/users/7/disable")).andExpect(status().isForbidden());
    mvc.perform(post("/users/7/disable").with(csrf())).andExpect(status().is3xxRedirection());
}

Extensions

  • Add a "remember me" cookie only for low-risk pages and re-ask for the password before disabling accounts (step-up authentication).
  • Add multi-factor authentication for ADMIN.
  • Record every admin action with an audit listener (audit events).
  • Review the finished app with the hardening checklist.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a role hierarchy such as ADMIN > SUPPORT > STAFF save you from?

    Higher roles automatically get the authorities of lower roles, so each rule names only the minimum role.
  2. 2. How does changing the session id at login help?

    That is session fixation protection, enabled by default in Spring Security.
  3. 3. A support user posts to /users/7/disable with a valid CSRF token. What happens?

    CSRF only proves the request came from your own page; authorization is a separate check.
  4. 4. Which test helper adds a valid CSRF token to a MockMvc request?

    SecurityMockMvcRequestPostProcessors.csrf() supplies a valid token.

Summary

  • Browser apps keep form login, session cookies, session id rotation and CSRF tokens on.
  • Declare roles once with a hierarchy and put the strictest rules first.
  • CSRF protects against forged requests; roles decide who may act. You need both.
  • Test the forbidden paths as carefully as the allowed ones.

Next: Practice: reviewing Spring Security code