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; // Getters and setters }
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/**") // Disable CSRF for APIs ) .headers(headers -> headers .frameOptions().disable() // Allow H2 console ); 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
No authentication required (permitted to all).
POST /api/products
Requires ADMIN role.
Headers:
Authorization: Basic YWRtaW46YWRtaW4=
(Base64 ofadmin:admin
).
Explanation:
Security:
/api/products
is public;/api/products/**
requires ADMIN.In-memory users with BCrypt password encoding.
CSRF disabled for APIs (stateless).
API Design:
RESTful endpoints for product management.
H2 database for easy setup.
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:
Why use Spring Boot?
Answer: Simplifies configuration with auto-configuration, embedded servers, and starter dependencies.
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 athttp://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; // Getters/setters }
Why:
@Entity
: Maps the class to a database table.@Id
and@GeneratedValue
: Auto-generates primary keys.
Interview Question:
What is JPA?
Answer: Java Persistence API for ORM (Object-Relational Mapping).
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:
What is
JpaRepository
?
Answer: Interface providing CRUD and pagination methods for database operations.
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:
What is dependency injection?
Answer: Spring manages object creation and dependencies (e.g.,@Autowired
).
6. REST Controller
@RestController @RequestMapping("/api/products") public class ProductController { @Autowired private ProductService productService; @GetMapping public List<Product> getAllProducts() { return productService.getAllProducts(); } }
Why:
@RestController
: Combines@Controller
and@ResponseBody
(returns JSON/XML).@GetMapping
: Maps HTTP GET requests to/api/products
.
Interview Question:
What is the difference between
@Controller
and@RestController
?
Answer:@RestController
automatically serializes return objects to JSON/XML.
7. Security Configuration
@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers("/api/products").permitAll() // Public access .requestMatchers("/api/products/**").hasRole("ADMIN") // Admin-only .anyRequest().authenticated() ) .httpBasic(Customizer.withDefaults()) // Basic Auth .csrf(csrf -> csrf.ignoringRequestMatchers("/api/**")); // Disable CSRF for APIs 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 theADMIN
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
)No authentication required.
Admin-Only Endpoint (POST
/api/products
)Headers:
Authorization: Basic YWRtaW46YWRtaW4=
(Base64-encoded
admin:admin
)
Interview Question:
How does Basic Authentication work?
Answer: Credentials are sent in theAuthorization
header asBasic <base64(username:password)>
.
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:
Use JPA/Hibernate to avoid SQL injection.
Prefer
PreparedStatement
over raw SQL.
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
andLinkedList
?ArrayList
uses a dynamic array (faster for random access).LinkedList
uses a doubly linked list (faster for insertions/deletions).
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(); // Runtime polymorphism a.sound(); // Output: Bark
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?
Servlet: Java code with HTML (handles logic).
JSP: HTML with Java code (for presentation).
What is a
ServletContext
?Shared across the application (e.g., for storing global parameters).
Explain the JPA lifecycle methods (
@PrePersist
,@PostLoad
).@Entity public class Product { @PrePersist public void beforeSave() { /* Logic before saving */ } }
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
?@Component
: Auto-detected by Spring scan (class-level).@Bean
: Manually defined in a@Configuration
class (method-level).
How does Spring MVC handle a request?
Request → DispatcherServlet → Controller → Model → ViewResolver → Response.
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?
Auto-configuration, embedded servers, starter dependencies, and opinionated defaults.
What is the purpose of
spring-boot-starter-parent
?Parent POM for dependency management and default configurations.
How to externalize configuration?
Use
application.properties
orapplication.yml
for environment-specific settings.
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:
Use
try-with-resources
for JDBC connections.Prefer
StringBuilder
overString
concatenation in loops.
Spring:
Use constructor injection instead of field injection.
Leverage
@Transactional
for database operations.
Spring Boot:
Use profiles (
@Profile("dev")
) for environment-specific config.Monitor APIs with Spring Boot Actuator.
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.
No comments:
Post a Comment