Java Interview Questions: Security & API Implementation with Example Setup

 

Common Interview Questions on Security: Let’s break down Core JavaSpring BootJava/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.

  1. Authentication vs. Authorization

    • Authentication: Verifying user identity (e.g., username/password).

    • Authorization: Granting access to resources based on roles (e.g., ADMIN, USER).

  2. How to secure a Java web application?
    Use frameworks like Spring Security to enforce authentication, authorization, CSRF protection, and session management.

  3. Prevent SQL Injection
    Use prepared statements or JPA/Hibernate to avoid concatenating SQL queries.

  4. Explain CSRF Protection
    Spring Security provides CSRF tokens for state-changing requests (disabled for stateless APIs).

Common API Questions:

  1. REST Principles
    Stateless, resource-based URLs (e.g., /api/products), HTTP methods (GET, POST), JSON/XML responses.

  2. Create an API in Spring Boot
    Use @RestController, define endpoints with @GetMapping@PostMapping, etc.

  3. 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):

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)

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

java
@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

java
public interface ProductRepository extends JpaRepository<Product, Long> { }

Step 5: Service Layer

java
@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

java
@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

java
@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:

  1. GET /api/products

    • No authentication required (permitted to all).

  2. POST /api/products

    • Requires ADMIN role.

    • Headers: Authorization: Basic YWRtaW46YWRtaW4= (Base64 of admin: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)

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: createupdatevalidate, etc.).


3. Entity Class

java
@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

java
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

java
@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

java
@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

java
@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 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:

  1. Why disable CSRF for APIs?
    Answer: CSRF protects against browser-based attacks. APIs (stateless) use tokens like JWT instead.

  2. What is UserDetailsService?
    Answer: Interface to load user-specific data (e.g., from a database or in-memory).


8. Testing with Postman

Example Requests:

  1. Public Endpoint (GET /api/products)

    • No authentication required.

  2. 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 the Authorization header as Basic <base64(username:password)>.


Key Takeaways for Interviews

  1. Security:

    • Use Spring Security for RBAC (Role-Based Access Control).

    • Always hash passwords (e.g., BCrypt).

    • Disable CSRF for stateless APIs.

  2. APIs:

    • Follow REST conventions (resource URLs, HTTP methods).

    • Separate layers (Controller → Service → Repository).

  3. 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: securityAPI design, and database integration. Practice explaining each layer and its purpose!



1. Core Java

Key Concepts:

  • OOP Principles: Abstraction, Encapsulation, Inheritance, Polymorphism.

  • CollectionsListSetMapQueue, and their implementations (ArrayListHashMap, etc.).

  • MultithreadingThread class, RunnableExecutorService, synchronization.

  • Exception Handlingtry-catch-finally, custom exceptions.

  • JDBC: Connecting to databases using DriverManagerDataSource, etc.

Interview Questions:

  1. What is the difference between ArrayList and LinkedList?

    • ArrayList uses a dynamic array (faster for random access).

    • LinkedList uses a doubly linked list (faster for insertions/deletions).

  2. Explain polymorphism with an example.

    java
    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  
  3. 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:

  1. What is the difference between a servlet and a JSP?

    • Servlet: Java code with HTML (handles logic).

    • JSP: HTML with Java code (for presentation).

  2. What is a ServletContext?

    • Shared across the application (e.g., for storing global parameters).

  3. Explain the JPA lifecycle methods (@PrePersist@PostLoad).

    java
    @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:

  1. 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).

  2. How does Spring MVC handle a request?

    • Request → DispatcherServlet → Controller → Model → ViewResolver → Response.

  3. 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

java
@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:

  1. How does Spring Boot simplify development?

    • Auto-configuration, embedded servers, starter dependencies, and opinionated defaults.

  2. What is the purpose of spring-boot-starter-parent?

    • Parent POM for dependency management and default configurations.

  3. How to externalize configuration?

    • Use application.properties or application.yml for environment-specific settings.


5. Key Differences

Java/J2EESpringSpring Boot
Heavyweight (EJB, JNDI)Lightweight, modularZero-config, opinionated
XML configurationXML/AnnotationsAuto-configuration
Complex setupSimplified DI and AOPEmbedded server

6. Common Interview Scenarios

Scenario 1: Secure a Spring Boot API with JWT

Steps:

  1. Add spring-boot-starter-security and JWT library (e.g., jjwt).

  2. Create a JwtFilter to validate tokens.

  3. Configure SecurityFilterChain to authenticate requests.

Code Snippet:

java
@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:

  1. Define an Entity (e.g., User).

  2. Extend JpaRepository<User, Long>.

  3. Use @Service and @RestController to expose endpoints.


7. Best Practices

  1. Core Java:

    • Use try-with-resources for JDBC connections.

    • Prefer StringBuilder over String concatenation in loops.

  2. Spring:

    • Use constructor injection instead of field injection.

    • Leverage @Transactional for database operations.

  3. 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

  1. Core Java: Practice multithreading, collections, and exception handling.

  2. Spring: Understand DI, AOP, and MVC flow.

  3. Spring Boot: Know auto-configuration, starters, and Actuator.

  4. Java/J2EE: Be ready to compare with Spring-based solutions.

No comments:

Post a Comment

Handling multiple devices for a single user in a token-based authentication system (like JWT or OAuth2)

  1. Use Refresh Tokens with Access Tokens Access tokens should be short-lived (e.g., 15 minutes). Refresh tokens should be long-liv...

Best for you