Q1. What is Spring Security?
Spring Security is a powerful authentication and access-control framework. It provides comprehensive security services for Java applications, including authentication (who are you?), authorization (what can you do?), and protection against common attacks like CSRF, session fixation, etc.
Q2. How do you configure basic authentication in Spring Security?
Create a security configuration class extending WebSecurityConfigurerAdapter (deprecated in recent versions) or using SecurityFilterChain bean. Example:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and().formLogin();
return http.build();
}
Q3. What is UserDetailsService?
UserDetailsService is an interface used to retrieve user-related data. It has a single method loadUserByUsername that returns a UserDetails object. You can implement it to provide custom user authentication from a database or other source.
Q4. What is the difference between authentication and authorization?
Authentication verifies the identity of a user (who you are). Authorization determines what resources a user can access (what you can do). Spring Security supports both.
Q5. What is BCryptPasswordEncoder?
It's an implementation of PasswordEncoder that uses the BCrypt strong hashing function. It's recommended for storing passwords because it incorporates salt and is computationally expensive to crack. Use it in your security configuration to encode passwords.
