How can you implement authentication and authorization in Spring Boot?

Authentication and authorization in Spring Boot are implemented through Spring Security, which verifies who a user is (authentication) and then decides what they're allowed to do (authorization), configured declaratively via a SecurityFilterChain bean.

Key Points: • Authentication sources can be a database (via UserDetailsService), LDAP, in-memory users, or an external OAuth2 provider. • spring-boot-starter-security auto-configures a sensible default (form login, basic auth) that you then customize. • Authorization rules are declared with authorizeHttpRequests(), mapping URL patterns to required roles or authorities. • Method-level annotations like @PreAuthorize add finer-grained authorization beyond URL matching. • Passwords are never stored raw—PasswordEncoder (typically BCrypt) handles secure hashing during authentication.

Example: A simple app defines a UserDetailsService backed by a JPA repository for authentication, and a SecurityFilterChain bean that restricts /admin/** to ROLE_ADMIN while leaving /public/** open to everyone.

Code Example:

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

Interview Tip: A concise interview answer is:

"In Spring Boot, Spring Security handles both concerns: authentication verifies identity through a source like a database or OAuth2 provider, and authorization is declared through authorizeHttpRequests() mapping URLs to required roles, optionally refined further with method-level annotations like @PreAuthorize."