Spring Security Authentication, Authorization, Filters is an important Spring topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.
For this page, focus on what problem Spring Security Authentication, Authorization, Filters solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .
A strong understanding of Spring Security Authentication, Authorization, Filters should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.
Spring Security Authentication Authorization Filters should be studied as a practical Spring lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.
In the spring > spring-security page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.
Spring Security is a powerful and highly customizable authentication and access-control framework for Java applications. It is the de-facto standard for securing Spring-based applications. It provides:
package com.example.config;
import org.springframework.context.annotation.*;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
// Authorization rules
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/home", "/register", "/css/**", "/js/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/api/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
)
// Form login
.formLogin(form -> form
.loginPage("/login")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/dashboard", true)
.failureUrl("/login?error=true")
.permitAll()
)
// Logout
.logout(logout -> logout
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout=true")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
.permitAll()
)
// HTTP Basic auth (for REST APIs)
// .httpBasic(Customizer.withDefaults())
// CSRF protection (disable for REST APIs)
// .csrf(csrf -> csrf.disable())
;
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12); // Strength 12
}
}
package com.example.security;
import com.example.entity.User;
import com.example.repository.UserRepository;
import org.springframework.security.core.*;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.*;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private final UserRepository userRepository;
public UserDetailsServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));
// Convert roles to GrantedAuthority
List<GrantedAuthority> authorities = List.of(
new SimpleGrantedAuthority("ROLE_" + user.getRole().name())
);
return new org.springframework.security.core.userdetails.User(
user.getUsername(),
user.getPassword(), // BCrypt hashed password
authorities
);
}
}
// Registration service - hash password before saving
@Service
public class RegistrationService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public RegistrationService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
public User register(String username, String email, String rawPassword) {
User user = new User();
user.setUsername(username);
user.setEmail(email);
user.setPassword(passwordEncoder.encode(rawPassword)); // Hash!
user.setRole(User.Role.USER);
return userRepository.save(user);
}
}
// Enable method security in config:
// @EnableMethodSecurity(prePostEnabled = true)
@Service
public class AdminService {
// Only ADMIN role can call this
@PreAuthorize("hasRole('ADMIN')")
public List<User> getAllUsers() {
return userRepository.findAll();
}
// User can only access their own data
@PreAuthorize("hasRole('ADMIN') or #username == authentication.name")
public User getUserProfile(String username) {
return userRepository.findByUsername(username).orElseThrow();
}
// Check after method returns
@PostAuthorize("returnObject.username == authentication.name or hasRole('ADMIN')")
public User getUser(Long id) {
return userRepository.findById(id).orElseThrow();
}
// Secure with SpEL expression
@PreAuthorize("hasRole('ADMIN') and #user.role != 'ADMIN'")
public void deleteUser(User user) {
userRepository.delete(user);
}
}
When studying Spring Security Authentication, Authorization, Filters, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.
In Spring, Spring Security Authentication, Authorization, Filters becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.
class SpringSecurityAuthenticationAuthorizationFiltersReview {
public static void main(String[] args) {
String state = "ready";
System.out.println("Spring Security Authentication Authorization Filters: " + state);
}
}
String value = null;
if (value == null) {
System.out.println("Spring Security Authentication Authorization Filters: handle the missing value before continuing");
}
Memorizing Spring Security Authentication Authorization Filters without the situation where it is useful.
Connect Spring Security Authentication Authorization Filters to a concrete Spring task.
Testing Spring Security Authentication Authorization Filters only with the perfect input.
Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Changing code before reading the visible symptom or error message.
Inspect the output, state, configuration, or stack trace connected to Spring Security Authentication Authorization Filters.
Memorizing Spring Security Authentication Authorization Filters without the situation where it is useful.
Connect Spring Security Authentication Authorization Filters to a concrete Spring task.
The common mistake is memorizing syntax without understanding when the behavior changes or fails.
Remember the problem it solves in Spring, then attach the syntax or steps to that problem.
You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.
They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.
Explore 500+ free tutorials across 20+ languages and frameworks.