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

Tuesday, 23 September 2025

Wednesday, 10 September 2025

Runnable ,callable ,Executer service Thred example

 import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class RunnableAndThread implements Runnable , Callable<Integer> {
@Override
public void run() {
System.out.println("hello");
}

public void myrun() {
System.out.println("hellopawan");
}
@Override
public Integer call() {
return 50;
}

public static void main(String args[]) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit((Runnable) new RunnableAndThread());
executor.submit(()->new RunnableAndThread().myrun());
Future<Integer> future = executor.submit((Callable<Integer>) new RunnableAndThread());
System.out.println("Callable result: " + future.get());
//Thread runnableAndThread = new Thread(()->new RunnableAndThread().myrun());
//runnableAndThread.start();
//Thread runnableAndThread1 = new Thread(new RunnableAndThread());
//runnableAndThread1.start();
}
}

Tuesday, 5 August 2025

Amazon SES RAW email

 https://docs.aws.amazon.com/ses/latest/dg/send-email-raw.html


package com.amazonaws.samples;


import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.PrintStream;

import java.nio.ByteBuffer;

import java.util.Properties;


// JavaMail libraries. Download the JavaMail API 

// from https://javaee.github.io/javamail/

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Session;

import javax.mail.internet.AddressException;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;


// AWS SDK libraries. Download the AWS SDK for Java 

// from https://aws.amazon.com/sdk-for-java

import com.amazonaws.regions.Regions;

import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;

import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;

import com.amazonaws.services.simpleemail.model.RawMessage;

import com.amazonaws.services.simpleemail.model.SendRawEmailRequest;


public class AmazonSESSample {


// Replace sender@example.com with your "From" address.

// This address must be verified with Amazon SES.

private static String SENDER = "Sender Name <sender@example.com>";


// Replace recipient@example.com with a "To" address. If your account 

// is still in the sandbox, this address must be verified.

private static String RECIPIENT = "recipient@example.com";


// Specify a configuration set. If you do not want to use a configuration

// set, comment the following variable, and the 

// ConfigurationSetName=CONFIGURATION_SET argument below.

private static String CONFIGURATION_SET = "ConfigSet";


// The subject line for the email.

private static String SUBJECT = "Customer service contact info";


// The full path to the file that will be attached to the email.

// If you're using Windows, escape backslashes as shown in this variable.

private static String ATTACHMENT = "C:\\Users\\sender\\customers-to-contact.xlsx";


// The email body for recipients with non-HTML email clients.

private static String BODY_TEXT = "Hello,\r\n"

                                        + "Please see the attached file for a list "

                                        + "of customers to contact.";


// The HTML body of the email.

private static String BODY_HTML = "<html>"

                                        + "<head></head>"

                                        + "<body>"

                                        + "<h1>Hello!</h1>"

                                        + "<p>Please see the attached file for a "

                                        + "list of customers to contact.</p>"

                                        + "</body>"

                                        + "</html>";


    public static void main(String[] args) throws AddressException, MessagingException, IOException {

           

    Session session = Session.getDefaultInstance(new Properties());

        

        // Create a new MimeMessage object.

        MimeMessage message = new MimeMessage(session);

        

        // Add subject, from and to lines.

        message.setSubject(SUBJECT, "UTF-8");

        message.setFrom(new InternetAddress(SENDER));

        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(RECIPIENT));


        // Create a multipart/alternative child container.

        MimeMultipart msg_body = new MimeMultipart("alternative");

        

        // Create a wrapper for the HTML and text parts.        

        MimeBodyPart wrap = new MimeBodyPart();

        

        // Define the text part.

        MimeBodyPart textPart = new MimeBodyPart();

        textPart.setContent(BODY_TEXT, "text/plain; charset=UTF-8");

                

        // Define the HTML part.

        MimeBodyPart htmlPart = new MimeBodyPart();

        htmlPart.setContent(BODY_HTML,"text/html; charset=UTF-8");

                

        // Add the text and HTML parts to the child container.

        msg_body.addBodyPart(textPart);

        msg_body.addBodyPart(htmlPart);

        

        // Add the child container to the wrapper object.

        wrap.setContent(msg_body);

        

        // Create a multipart/mixed parent container.

        MimeMultipart msg = new MimeMultipart("mixed");

        

        // Add the parent container to the message.

        message.setContent(msg);

        

        // Add the multipart/alternative part to the message.

        msg.addBodyPart(wrap);

        

        // Define the attachment

        MimeBodyPart att = new MimeBodyPart();

        DataSource fds = new FileDataSource(ATTACHMENT);

        att.setDataHandler(new DataHandler(fds));

        att.setFileName(fds.getName());

        

        // Add the attachment to the message.

        msg.addBodyPart(att);


        // Try to send the email.

        try {

            System.out.println("Attempting to send an email through Amazon SES "

                              +"using the AWS SDK for Java...");


            // Instantiate an Amazon SES client, which will make the service 

            // call with the supplied AWS credentials.

            AmazonSimpleEmailService client = 

                    AmazonSimpleEmailServiceClientBuilder.standard()

                    // Replace US_WEST_2 with the AWS Region you're using for

                    // Amazon SES.

                    .withRegion(Regions.US_WEST_2).build();

            

            // Print the raw email content on the console

            PrintStream out = System.out;

            message.writeTo(out);


            // Send the email.

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            message.writeTo(outputStream);

            RawMessage rawMessage = 

            new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));


            SendRawEmailRequest rawEmailRequest = 

            new SendRawEmailRequest(rawMessage)

                .withConfigurationSetName(CONFIGURATION_SET);

            

            client.sendRawEmail(rawEmailRequest);

            System.out.println("Email sent!");

        // Display an error if something goes wrong.

        } catch (Exception ex) {

          System.out.println("Email Failed");

            System.err.println("Error message: " + ex.getMessage());

            ex.printStackTrace();

        }

    }

}

Thursday, 10 July 2025

Spring bean configuration with xml and java

If you want o use spring bean configuration with xml then you have to create bean.xml file