Spring Boot Security Interview Questions and Answers
1. Overview of Spring Security
Q1: What is Spring Security?
Answer: Spring Security is a customizable authentication and access control framework for Java applications. It provides features like:
Authentication: Verifying user identity.
Authorization: Managing user access to resources.
Protection: Preventing vulnerabilities like CSRF, XSS, and more.
Customizability: Highly configurable for various security requirements.
2. Adding Spring Security
Q2: How do you add Spring Security to a Spring Boot application?
Answer: Include the dependency in your pom.xml
:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
Spring Boot auto-configures a basic authentication setup with default credentials (user
and an autogenerated password in logs).
3. Implementing Basic Authentication
Q3: How can you implement basic authentication in a Spring Boot application?
Answer: Extend the WebSecurityConfigurerAdapter
class and override the configure(HttpSecurity http)
method.
Example:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/public").permitAll() // Open endpoint
.anyRequest().authenticated() // Secured endpoints
.and()
.httpBasic(); // Enables Basic Authentication
}
}
4. JWT-Based Authentication
Q4: How do you implement JWT authentication in Spring Boot?
Answer: JWT (JSON Web Tokens) enables stateless authentication by passing user details as a signed token.
Steps:
Add Dependencies:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
JWT Utility Class:
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class JwtUtil {
private final String SECRET_KEY = "secret_key";
public String generateToken(String username) {
return Jwts.builder()
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) // 10 hours
.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
.compact();
}
public String extractUsername(String token) {
return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getSubject();
}
public boolean validateToken(String token, String username) {
return username.equals(extractUsername(token)) && !isTokenExpired(token);
}
private boolean isTokenExpired(String token) {
return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getExpiration().before(new Date());
}
}
JWT Request Filter:
@Component
public class JwtFilter extends OncePerRequestFilter {
private final JwtUtil jwtUtil;
public JwtFilter(JwtUtil jwtUtil) {
this.jwtUtil = jwtUtil;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
String authHeader = request.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String jwt = authHeader.substring(7);
String username = jwtUtil.extractUsername(jwt);
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
chain.doFilter(request, response);
}
}
Integrate JWT with Security Config:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final JwtFilter jwtFilter;
public SecurityConfig(JwtFilter jwtFilter) {
this.jwtFilter = jwtFilter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/authenticate").permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
}
}
5. Role-Based Authorization
Q5: How do you manage roles and permissions in Spring Security?
Answer: Use @PreAuthorize
or configure roles in WebSecurityConfigurerAdapter
.
Example Code:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
6. CSRF Protection
Q6: What is CSRF, and how does Spring Security protect against it?
Answer:
CSRF (Cross-Site Request Forgery) occurs when attackers trick users into performing actions on a web application without their consent.
Spring Security protects against CSRF by default using tokens.
Disabling CSRF (not recommended for non-API apps):
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
7. Password Hashing
Q7: How do you securely store passwords in Spring Boot?
Answer: Use a strong hashing algorithm like BCrypt.
Example:
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
8. OAuth2 Integration
Q8: How do you implement OAuth2 in Spring Boot?
Answer:
Add
spring-boot-starter-oauth2-client
dependency.Configure OAuth2 properties in
application.properties
:
spring.security.oauth2.client.registration.google.client-id=your-client-id
spring.security.oauth2.client.registration.google.client-secret=your-client-secret
spring.security.oauth2.client.registration.google.redirect-uri=http://localhost:8080/login/oauth2/code/google
Secure routes using OAuth2:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.oauth2Login()
.and()
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated();
}
9. Session Management
Q9: How does Spring Security handle session management?
Answer:
Spring Security manages sessions to prevent Session Fixation attacks.
Use
SessionCreationPolicy
for stateless applications (e.g., REST APIs).
Example (Stateless Session):
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
10. Security Best Practices
Q10: What are some Spring Security best practices?
Enable HTTPS: Enforce secure communication.
Use Strong Hashing: Always hash passwords with
BCryptPasswordEncoder
.Restrict Endpoint Access: Protect sensitive endpoints with role-based authorization.
Validate Input: Prevent injection attacks.
Limit Failed Login Attempts: Lock accounts temporarily after repeated failures.
Implement Rate Limiting: Use tools like
Bucket4j
to prevent abuse.Secure Sensitive Data: Use environment variables or vaults for sensitive configurations.