Common Interview Questions on Security: Let’s break down Core Java, Spring Boot, Java/J2EE, and Spring with their relationships, key features, and examples to prepare you for interviews. I'll also include common interview questions and practical use cases.
Authentication vs. Authorization
Authentication: Verifying user identity (e.g., username/password).
Authorization: Granting access to resources based on roles (e.g., ADMIN, USER).
How to secure a Java web application?
Use frameworks like Spring Security to enforce authentication, authorization, CSRF protection, and session management.
Prevent SQL Injection
Use prepared statements or JPA/Hibernate to avoid concatenating SQL queries.
Explain CSRF Protection
Spring Security provides CSRF tokens for state-changing requests (disabled for stateless APIs).
Common API Questions:
REST Principles
Stateless, resource-based URLs (e.g., /api/products
), HTTP methods (GET, POST), JSON/XML responses.
Create an API in Spring Boot
Use @RestController
, define endpoints with @GetMapping
, @PostMapping
, etc.
API Versioning
URL path (/api/v1/products
), headers, or media type versioning.
Full Example: Secured REST API with Spring Boot
Step 1: Project Setup (Spring Boot 3.x)
Dependencies (Maven pom.xml
):
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
Step 2: Configure H2 Database (application.properties
)
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=update
Step 3: Entity Class
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
}
Step 4: JPA Repository
public interface ProductRepository extends JpaRepository<Product, Long> { }
Step 5: Service Layer
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
public List<Product> getAllProducts() {
return productRepository.findAll();
}
public Product createProduct(Product product) {
return productRepository.save(product);
}
}
Step 6: REST Controller
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping
public List<Product> getAllProducts() {
return productService.getAllProducts();
}
@PostMapping
public Product createProduct(@RequestBody Product product) {
return productService.createProduct(product);
}
}
Step 7: Security Configuration
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/products").permitAll()
.requestMatchers("/api/products/**").hasRole("ADMIN")
.requestMatchers("/h2-console/**").permitAll()
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults())
.csrf(csrf -> csrf
.ignoringRequestMatchers("/h2-console/**", "/api/**")
)
.headers(headers -> headers
.frameOptions().disable()
);
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.builder()
.username("user")
.password(passwordEncoder().encode("password"))
.roles("USER")
.build();
UserDetails admin = User.builder()
.username("admin")
.password(passwordEncoder().encode("admin"))
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Testing the API with Postman:
GET /api/products
POST /api/products
Explanation:
Security:
/api/products
is public; /api/products/**
requires ADMIN.
In-memory users with BCrypt password encoding.
CSRF disabled for APIs (stateless).
API Design:
1. Project Setup (Spring Boot 3.x)
Goal: Create a Spring Boot project with dependencies for web APIs, security, and database integration.
Dependencies (pom.xml
):
Spring Web: For REST API development (@RestController
, @GetMapping
, etc.).
Spring Security: For authentication/authorization.
Spring Data JPA: Simplifies database operations (e.g., JpaRepository
).
H2 Database: In-memory database for quick setup (no external DB needed).
Interview Question:
2. H2 Database Configuration (application.properties
)
spring.datasource.url=jdbc:h2:mem:testdb # In-memory database
spring.h2.console.enabled=true # Enable H2 web console
spring.jpa.hibernate.ddl-auto=update # Auto-create tables from entities
Why:
ddl-auto=update
: Automatically creates/updates database tables based on entity classes (useful for prototyping).
h2-console.enabled=true
: Allows access to the H2 web console at http://localhost:8080/h2-console
.
Interview Question:
What is ddl-auto
?
Answer: Configures Hibernate to auto-generate database schemas (options: create
, update
, validate
, etc.).
3. Entity Class
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
}
Why:
Interview Question:
4. JPA Repository
public interface ProductRepository extends JpaRepository<Product, Long> { }
Why:
Spring Data JPA provides CRUD operations out-of-the-box (e.g., save()
, findAll()
).
No need to write SQL queries manually.
Interview Question:
5. Service Layer
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
public List<Product> getAllProducts() {
return productRepository.findAll();
}
}
Why:
Business logic separation (controller handles HTTP, service handles logic).
@Autowired
: Injects the repository dependency (Spring IoC container).
Interview Question:
6. REST Controller
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping
public List<Product> getAllProducts() {
return productService.getAllProducts();
}
}
Why:
Interview Question:
7. Security Configuration
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/products").permitAll()
.requestMatchers("/api/products/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults())
.csrf(csrf -> csrf.ignoringRequestMatchers("/api/**"));
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails admin = User.builder()
.username("admin")
.password(passwordEncoder().encode("admin"))
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(admin);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Key Points:
authorizeHttpRequests
: Defines URL-based access rules.
hasRole("ADMIN")
: Restricts access to users with the ADMIN
role.
httpBasic
: Enables Basic Authentication (username/password in headers).
CSRF Disabled: APIs are stateless, so CSRF protection is unnecessary.
BCryptPasswordEncoder
: Securely hashes passwords (never store plain text!).
Interview Questions:
Why disable CSRF for APIs?
Answer: CSRF protects against browser-based attacks. APIs (stateless) use tokens like JWT instead.
What is UserDetailsService
?
Answer: Interface to load user-specific data (e.g., from a database or in-memory).
8. Testing with Postman
Example Requests:
Public Endpoint (GET /api/products
)
Admin-Only Endpoint (POST /api/products
)
Interview Question:
Key Takeaways for Interviews
Security:
Use Spring Security for RBAC (Role-Based Access Control).
Always hash passwords (e.g., BCrypt).
Disable CSRF for stateless APIs.
APIs:
Follow REST conventions (resource URLs, HTTP methods).
Separate layers (Controller → Service → Repository).
Database:
Common Pitfalls to Mention
Hardcoding credentials (use environment variables or Spring Vault).
Storing plain-text passwords (always hash!).
Exposing sensitive endpoints without authorization.
This setup covers fundamental Java interview topics: security, API design, and database integration. Practice explaining each layer and its purpose!
1. Core Java
Key Concepts:
OOP Principles: Abstraction, Encapsulation, Inheritance, Polymorphism.
Collections: List
, Set
, Map
, Queue
, and their implementations (ArrayList
, HashMap
, etc.).
Multithreading: Thread
class, Runnable
, ExecutorService
, synchronization.
Exception Handling: try-catch-finally
, custom exceptions.
JDBC: Connecting to databases using DriverManager
, DataSource
, etc.
Interview Questions:
What is the difference between ArrayList
and LinkedList
?
Explain polymorphism with an example.
class Animal { void sound() { System.out.println("Animal sound"); } }
class Dog extends Animal { void sound() { System.out.println("Bark"); } }
Animal a = new Dog();
a.sound();
How does the final
keyword work?
final
variable: Value can’t change.
final
method: Can’t be overridden.
final
class: Can’t be inherited.
2. Java/J2EE (Jakarta EE)
Key Concepts:
Servlets: Java classes handling HTTP requests/responses (e.g., HttpServlet
).
JSP: Java Server Pages for dynamic web content.
EJB: Enterprise JavaBeans for business logic (e.g., @Stateless
, @Stateful
).
JPA: Java Persistence API for ORM (e.g., Hibernate).
JMS: Java Messaging Service for asynchronous communication.
Interview Questions:
What is the difference between a servlet and a JSP?
What is a ServletContext
?
Explain the JPA lifecycle methods (@PrePersist
, @PostLoad
).
@Entity
public class Product {
@PrePersist
public void beforeSave() { }
}
3. Spring Framework
Key Concepts:
Dependency Injection (DI): Inversion of Control (IoC) via @Autowired
, @Component
, etc.
AOP: Aspect-Oriented Programming for cross-cutting concerns (logging, security).
Spring MVC: Model-View-Controller for web apps (e.g., @Controller
, @RequestMapping
).
Spring Data: Simplifies database access (e.g., JpaRepository
).
Interview Questions:
What is the difference between @Component
and @Bean
?
How does Spring MVC handle a request?
What is a BeanFactory
vs. ApplicationContext
?
BeanFactory
: Basic IoC container (lazy initialization).
ApplicationContext
: Advanced (pre-loads beans, supports AOP, events, etc.).
4. Spring Boot
Key Concepts:
Auto-Configuration: Automatically configures beans based on classpath.
Starters: Pre-defined dependencies (e.g., spring-boot-starter-web
).
Embedded Servers: Tomcat, Jetty, Undertow.
Actuator: Monitoring and metrics endpoints.
Example: Simple Spring Boot REST API
@SpringBootApplication
public class DemoApp {
public static void main(String[] args) {
SpringApplication.run(DemoApp.class, args);
}
}
@RestController
class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot!";
}
}
Interview Questions:
How does Spring Boot simplify development?
What is the purpose of spring-boot-starter-parent
?
How to externalize configuration?
5. Key Differences
Java/J2EE | Spring | Spring Boot |
---|
Heavyweight (EJB, JNDI) | Lightweight, modular | Zero-config, opinionated |
XML configuration | XML/Annotations | Auto-configuration |
Complex setup | Simplified DI and AOP | Embedded server |
6. Common Interview Scenarios
Scenario 1: Secure a Spring Boot API with JWT
Steps:
Add spring-boot-starter-security
and JWT library (e.g., jjwt
).
Create a JwtFilter
to validate tokens.
Configure SecurityFilterChain
to authenticate requests.
Code Snippet:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/auth/login").permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(jwtFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}
Scenario 2: Implement CRUD with Spring Data JPA
Steps:
Define an Entity
(e.g., User
).
Extend JpaRepository<User, Long>
.
Use @Service
and @RestController
to expose endpoints.
7. Best Practices
Core Java:
Spring:
Spring Boot:
8. Common Tools & Frameworks
Build Tools: Maven, Gradle.
Testing: JUnit, Mockito, Testcontainers.
Security: Spring Security, OAuth2, JWT.
Database: Hibernate, Flyway, Liquibase.
9. Interview Prep Checklist
Core Java: Practice multithreading, collections, and exception handling.
Spring: Understand DI, AOP, and MVC flow.
Spring Boot: Know auto-configuration, starters, and Actuator.
Java/J2EE: Be ready to compare with Spring-based solutions.