Thursday, 9 October 2025

Spring security interview question.

 

🧩 1. Core Spring Security Architecture

Q1. What are the main components of Spring Security?
Q2. Explain the Spring Security filter chain and how it works internally.
Q3. What is the difference between FilterChainProxy and DelegatingFilterProxy?
Q4. How does Spring Security integrate with the Servlet container?
Q5. What is the role of SecurityContext and SecurityContextHolder?


🔐 2. Authentication & Authorization

Q6. Explain the authentication flow in Spring Security.
Q7. What is the difference between AuthenticationManager and AuthenticationProvider?
Q8. How does Spring Security handle authorization decisions?
Q9. What is the purpose of AccessDecisionManager and AccessDecisionVoter?
Q10. How do you customize authentication (e.g., using database, LDAP, JWT, or OAuth)?


💾 3. JWT (JSON Web Token) & Stateless Authentication

Q11. Explain how JWT-based authentication works in Spring Security.
Q12. What are the pros and cons of using JWT vs session-based authentication?
Q13. How do you implement token invalidation (logout) in JWT-based systems?
Q14. How can you refresh JWT tokens securely?
Q15. How would you prevent token replay attacks?


🧰 4. Configuration Approaches

Q16. What’s the difference between WebSecurityConfigurerAdapter and the new SecurityFilterChain approach (Spring Security 5.7+)?
Q17. How do you configure multiple HttpSecurity instances for different API paths?
Q18. How would you disable security for a specific endpoint (e.g., /health, /actuator)?
Q19. How to secure REST APIs using Spring Security annotations (@PreAuthorize, @Secured)?
Q20. Explain method-level vs URL-level security.


⚙️ 5. Customization & Extensibility

Q21. How do you create a custom authentication filter?
Q22. How do you plug in a custom UserDetailsService?
Q23. Explain how to add custom claims to JWT during login.
Q24. How do you handle multi-factor authentication (MFA) in Spring Security?
Q25. How can you secure microservices communicating over REST (e.g., internal JWT validation)?


🧠 6. Advanced Concepts

Q26. Explain SecurityContextPersistenceFilter and its purpose.
Q27. What is AnonymousAuthenticationFilter and when does it come into play?
Q28. How does Spring Security handle CSRF protection in REST APIs?
Q29. Explain how CORS and Spring Security interact.
Q30. What are stateless sessions, and how are they configured?


🧩 7. OAuth2 / OpenID Connect

Q31. Explain the OAuth2 authorization code flow.
Q32. What are the key differences between OAuth2 and OpenID Connect?
Q33. How would you secure a resource server and client application using Spring Security OAuth2?
Q34. What’s the difference between BearerTokenAuthenticationFilter and BasicAuthenticationFilter?
Q35. How do you refresh access tokens securely in OAuth2?


🧱 8. Security Best Practices

Q36. How do you prevent brute-force attacks in Spring Security?
Q37. How do you implement rate-limiting or IP-based blocking?
Q38. How do you store passwords securely in the database?
Q39. What are common security misconfigurations you’ve seen in Spring projects?
Q40. How do you secure WebSockets with Spring Security?


☁️ 9. Real-World & Integration

Q41. How would you design authentication for a microservices architecture (e.g., using JWT + Redis)?
Q42. How can you propagate authentication across multiple services (SSO)?
Q43. How to integrate Spring Security with AWS Cognito or Azure AD?
Q44. How do you secure actuator endpoints in production?
Q45. How do you test secured endpoints using JUnit and Mockito?


🧪 10. Troubleshooting & Debugging

Q46. How do you debug 403 Forbidden issues in Spring Security?
Q47. How do you log authentication and authorization events?
Q48. How do you verify your filter order in the Spring Security chain?
Q49. What’s the difference between @WithMockUser and @WithUserDetails in testing?
Q50. How would you profile or optimize security filters for performance?


✅ Bonus: Scenario-Based Questions

  1. You need to allow multiple concurrent logins per user, but also support logout from all sessions — how do you implement it?

  2. You want to support JWT authentication but also allow API key-based access for internal systems — how would you design it?

  3. You want to cache user roles and permissions to avoid frequent DB hits — how would you do that securely?

  4. You want to secure communication between two Spring Boot microservices — what’s your approach (TLS, JWT, OAuth2)?

  5. How would you audit who accessed which endpoint and when?


Would you like me to create a PDF or a structured study sheet (with answers and diagrams for each topic like JWT, filter chain, etc.)?
It’s perfect for 10+ yrs Spring Security interview prep.

Friday, 3 October 2025

How to Create a Pure Java Service-Layer JAR from a Spring Boot Project

When working on a Spring Boot application, the service layer often contains the business logic that you may want to reuse in other projects. But what if you want to create a JAR of only the service layer and use it in a plain Java project without any Spring dependencies? This guide walks you through the process step by step.


Why Separate the Service Layer?

Separating the service layer into its own module or project has several advantages:

  • Reusability: You can use it in multiple applications, including plain Java apps.

  • Decoupling: Keeps business logic separate from controllers or web-specific code.

  • Simpler Testing: Service logic can be tested independently of web or Spring Boot context.

Step 1: Remove Spring Dependencies

Spring annotations like @Service, @Component, @Autowired, or @Transactional won’t work in a plain Java application because they rely on Spring’s dependency injection and application context.

You need to:

  • Remove all Spring annotations.

  • Replace @Autowired dependencies with constructor or setter injection.

  • Handle transactions manually if needed.

Before (Spring Boot Service):

@Service

public class MyService {


    @Autowired

    private MyRepository repo;


    @Transactional

    public void doSomething() {

        repo.saveData();

    }

}

After (Plain Java Service):
public class MyService {

    private final MyRepository repo;

    public MyService(MyRepository repo) {
        this.repo = repo;
    }

    public void doSomething() {
        repo.saveData();
    }
}

Step 2: Prepare the Service Layer Module

Organize your project into a separate module for the service layer. Example structure:

my-app

├─ service-layer       <-- This will become the JAR

│   └─ src/main/java/... (all service classes)

│   └─ pom.xml

├─ web-layer           <-- Spring Boot app (controllers)

│   └─ src/main/java/...

│   └─ pom.xml

└─ pom.xml             <-- parent pom

Step 3: Create a Minimal pom.xml

Since you don’t want any Spring dependency, the pom.xml is very simple:

<project>

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>

    <artifactId>service-layer</artifactId>

    <version>1.0.0</version>

    <packaging>jar</packaging>


    <dependencies>

        <!-- Include only libraries your service actually needs -->

    </dependencies>

</project>

Only include libraries like JDBC drivers, Redis client, or other third-party APIs if your service uses them.

Step 4: Build the JAR

From the service-layer module folder, run:

mvn clean install

service-layer/target/service-layer-1.0.0.jar

This JAR now contains only your service layer and no controllers or Spring Boot classes.

Step 5: Use the JAR in a Plain Java Application

Add the JAR to your Java project classpath (or as a Maven dependency if installed in the local repo) and use it like any normal Java library:

public class Main {

    public static void main(String[] args) {

        MyRepository repo = new MyRepository();

        MyService service = new MyService(repo);


        service.doSomething();

    }

}

No Spring required, everything works in pure Java.


Key Takeaways

  1. Spring annotations do nothing in a plain Java app. To use your service layer outside Spring Boot, remove them.

  2. Use constructor or setter injection to manage dependencies manually.

  3. Keep only necessary dependencies in the service-layer pom.xml to make it lightweight.

  4. Build as a JAR using Maven and reuse it anywhere, including plain Java projects.

This approach allows you to decouple your business logic from Spring, making your service layer reusable, lightweight, and independent of any specific framework.


 

Stream Concat example

 https://www.netjstech.com/2022/01/java-stream-concat-with-examples.html


//code for fetch user assigned Specific design group
Long[] designGroupAssignedToUser = this.getDesignGroupBuUserId(user);
designGroupIds = Stream.concat(
Arrays.stream(Optional.ofNullable(designGroupIds).orElse(new Long[0])),
Arrays.stream(Optional.ofNullable(designGroupAssignedToUser).orElse(new Long[0]))
)
.distinct()
.toArray(Long[]::new);
//end of code