Labs ICT
โญ Pro Login

Spring Security Basics

Securing your application from the start.

Spring Security Basics

So you built an awesome API, but what's stopping anyone from accessing it? Without security, your endpoints are wide open like a shop with no doors. Spring Security is the gatekeeper that decides who gets in and who doesn't.

Don't worry โ€” Spring Security has a reputation for being complicated, but it's actually pretty logical once you understand the basics. Think of it as a series of checkpoints that every request must pass through.

What Spring Security Provides

Spring Security handles the heavy lifting for you: authentication (who are you?), authorization (what can you do?), and protection against common attacks like CSRF and session fixation. It's like hiring a professional security team for your app.

It also integrates seamlessly with Spring Boot. Just add the dependency and you get basic security out of the box. No configuration needed โ€” though you'll probably want to customize it eventually.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Security Filter Chain

Every HTTP request to your app goes through a chain of security filters. It's like airport security โ€” each filter checks something different. One checks your passport (authentication), another scans your bag (authorization), and another checks your ticket (CSRF token).

You configure this filter chain by defining a SecurityFilterChain bean. This is where you tell Spring Security what rules to enforce.

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/public/**").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
            )
            .httpBasic(Customizer.withDefaults());
        return http.build();
    }
}

Default Security Behavior

Out of the box, Spring Security locks everything down. Every endpoint requires authentication, and it generates a default user with a random password printed in the console. It's secure by default โ€” which is exactly what you want.

The default login page might surprise you if you're not expecting it. It's actually useful for development, but you'll want to replace it with your own login form or use stateless authentication like JWT tokens for production.

๐Ÿงช Quick Quiz

What is Spring Security?