0%
Security with Spring Security

Security

A filter chain in front of the DispatcherServlet.

15-20 min

Security with Spring Security

Security written by hand in controllers always fails the same way. You add a check at the top of every sensitive method — if (session.getAttribute("user") == null) return "redirect:/login"; — and it works, until the day a new method is written without that check. The flaw isn't in the security code: it's in its absence somewhere, and nothing signals that absence.

This is the difference in nature between an allowlist and a denylist approach. Protecting each screen individually means deciding that a screen is public by default. But screens multiply faster than code reviews, and an oversight triggers no error: the page works, it's simply accessible to everyone.

Spring Security reverses this default. It sits in front of the DispatcherServlet, as a chain of servlet filters, and applies a policy declared in a single place. A request to a URL not covered by the policy never reaches any controller: it is rejected by the infrastructure. Adding a screen therefore doesn't create a hole — at worst, it is inaccessible, which you notice immediately.

This lesson builds that policy for a Spring MVC application: a login form, users stored in a database with encoded passwords, roles, CSRF protection, and conditional display in Thymeleaf templates. It also emphasizes what has changed: since Spring Security 6, WebSecurityConfigurerAdapter no longer exists, and nearly all the examples you'll find online rely on it.

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!