SkillByAIOpen interactive version →

Lesson 20 / 25

Spring Security Basics

Authentication and authorisation.

A filter chain in front of your controllers

Adding spring-boot-starter-security secures every endpoint by default. Configure a SecurityFilterChain bean to decide which paths are public and which require authentication or roles, and how users authenticate: sessions with form login for web apps, or OAuth2 resource server with JWTs for APIs. Keep CSRF protection for browser sessions, store passwords only as strong hashes (the default delegating encoder uses bcrypt), and check authorisation in services for sensitive operations, not only on URLs.

Protect and observe

Spring Security secures endpoints; Micrometer and tracing show what the service is doing.

Figure 7.1 — Security, observability and resilience.

A filter chain for an API (sketch)

Not part of the built demo; check the Spring documentation for your version.

@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/actuator/health/**").permitAll()
            .requestMatchers(HttpMethod.GET, "/api/products/**").permitAll()
            .anyRequest().hasRole("ADMIN"))
        .oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()));
    return http.build();
}

Deny by default

Make anyRequest() require authentication and open specific paths explicitly, never the other way round.

Quick check: What happens when Spring Security is added with no configuration?

  • Nothing changes
  • All endpoints require authentication by default
  • All endpoints become public
  • The app fails to start
Answer

All endpoints require authentication by default — Secure by default.