How can you implement authentication and authorization in Spring Boot?

Authentication and authorization in Spring Boot are implemented with Spring Security, which verifies who a user is and then enforces what they're allowed to access.

Key Points: • Add spring-boot-starter-security, which secures all endpoints by default until configured otherwise. • Authentication sources can be in-memory (for demos), a database via UserDetailsService, or an external identity provider (OAuth2/JWT). • A SecurityFilterChain bean defines which endpoints require authentication and which roles can access which paths. • Passwords are always stored hashed (e.g. via BCryptPasswordEncoder), never in plain text. • Method-level authorization (@PreAuthorize) can complement URL-based rules for finer-grained control inside services.

Example: A REST API can require authentication for all /admin/** endpoints and restrict them to users with the ADMIN role, while leaving /public/** endpoints open, all defined declaratively in one SecurityFilterChain bean.

Code Example:

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

Interview Tip: A concise interview answer is:

"I'd add Spring Security, define a UserDetailsService backed by the database for authentication, and configure a SecurityFilterChain that maps URL patterns to required roles for authorization. Passwords are always hashed with BCrypt, and I add method-level @PreAuthorize checks where I need finer control than URL rules alone provide."