Security Basics with Spring Security
Add the Spring Security starter and every endpoint is locked by default. You then decide what's public and what needs sign-in.
Spring Security protects your API: it locks everything by default, then you open what should be public and restrict the rest by role. It also provides safe password hashing and standard sign-in methods.
Example
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/api/products/**").permitAll() // anyone can browse
.requestMatchers("/api/admin/**").hasRole("ADMIN") // only admins
.anyRequest().authenticated()) // everything else: signed in
.httpBasic(Customizer.withDefaults())
.csrf(csrf -> csrf.disable()); // only for stateless token-based APIs; keep CSRF on for browser sessions
return http.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder(); // bcrypt by default
}
}Storing passwords
Example
@Service
public class SignupService {
private final UserRepository users;
private final PasswordEncoder encoder;
public SignupService(UserRepository users, PasswordEncoder encoder) { this.users = users; this.encoder = encoder; }
public void signUp(String email, String password) {
String hash = encoder.encode(password); // like {bcrypt}$2a$10$... - never the real password
users.save(new AppUser(email, hash, "USER"));
}
}When the user signs in, Spring Security hashes what they typed and compares - you never store or log the real password.
Tokens for apps and SPAs
- Websites on the same domain usually use a session cookie (Spring Security's default form login)
- Mobile apps and separate front ends often send a JWT in the
Authorization: Bearer ...header. Spring Security's OAuth2 Resource Server starter checks JWTs for you - "Sign in with Google" uses the OAuth2 Client starter
Checklist
- HTTPS only in production
- Validate every input (lesson 6); use JPA or parameterised queries - never glue user input into SQL
- Check ownership: a user may only see their own orders, not just "any signed-in user"
- Limit sign-in attempts and keep dependencies updated (
./mvnw versions:display-dependency-updates)
Key points
- Configure access with a SecurityFilterChain.
- Store passwords with a PasswordEncoder (bcrypt).
- Check ownership of data, not just sign-in.
📝 Test yourself
1. After adding Spring Security, what happens to endpoints by default?
2. How should passwords be stored?
3. Fill in the method that only lets admins in:
.requestMatchers("/api/admin/**").("ADMIN")
