Spring Security Context Propagation – Complete Guide

Spring Security’s SecurityContext is the cornerstone of authentication and authorization in Spring applications. It stores critical user details like authentication token, granted authorities, and principal information. However, when operations span multiple threads—common in asynchronous processing or reactive programming—propagating this context becomes a significant challenge. This guide explores various strategies to ensure your security context travels correctly across thread boundaries.


Understanding SecurityContext and ThreadLocal

At the heart of Spring Security lies the SecurityContextHolder, which uses a ThreadLocal strategy by default. This means each thread maintains its own isolated security context, which works perfectly in standard synchronous request-response cycles but breaks down when new threads are spawned.

The SecurityContextHolder supports three persistence strategies:

  • MODE_THREADLOCAL: Default strategy where context is bound to the current thread
  • MODE_INHERITABLETHREADLOCAL: Context is inherited by child threads created by the current thread
  • MODE_GLOBAL: Single context shared across all threads (rarely used in production)
Continue reading Spring Security Context Propagation – Complete Guide

8086 Assembly Program to Compute Factorial of an Integer Using Recursion

This blog post will dive into a more advanced concept in 8086 assembly: computing the factorial of a number using recursion. Unlike iterative approaches using loops, recursion involves a procedure calling itself. This example highlights crucial concepts of stack management (PUSH and POP), procedure calls (CALL and RET), and conditional jumping to handle base cases. Let’s explore how the stack handles the “memory” of recursive calls!

; Program to calculate Factorial of a number using Recursion
; Input: num (e.g., 5)
; Output: result (e.g., 5! = 120 or 78h)

data segment
    num dw 0005h    ; The number to calculate factorial for (16-bit word)
    result dw ?     ; Variable to store the final 16-bit result
data ends

code segment
    assume cs:code, ds:data

start:
    mov ax, data
    mov ds, ax      ; Initialize Data Segment

    mov cx, num     ; Load the input number into CX register used as counter/argument
    mov ax, 0001h   ; Initialize accumulator AX to 1 (needed for multiplication)

    call factorial  ; Call the recursive procedure

    mov result, ax  ; Store final result from AX into memory variable
    int 3           ; Breakpoint to halt and check registers

;--- Recursive Procedure Definition ---
factorial proc near
    cmp cx, 1       ; BASE CASE: Check if number in CX is <= 1
    jbe base_case   ; If CX is 0 or 1, jump to base_case to return

    push cx         ; RECURSIVE STEP: Save current state of CX on STACK
    dec cx          ; Decrement CX to move towards base case (N-1)
    call factorial  ; Recursive Call: factorial(N-1)

    pop cx          ; UNWINDING: Restore the saved value of CX from STACK
    mul cx          ; AX = AX * CX. (Current Result * Current N)
    ret             ; Return to caller

base_case:
    mov ax, 1       ; Base case returns 1 (as 0! = 1 and 1! = 1)
    ret             ; Return to caller
factorial endp
;--------------------------------------

code ends
end start
Continue reading 8086 Assembly Program to Compute Factorial of an Integer Using Recursion

Master Custom Authentication Providers in Spring Security 6

Spring Security is the de facto standard for securing Java applications, offering robust support for OAuth2, LDAP, and standard form logins. But what happens when “standard” isn’t enough?

You might face a scenario where user credentials live in a legacy mainframe, a proprietary API, or a multi-tenant database with complex sharding rules. In these cases, the default DaoAuthenticationProvider fails. Trying to hack standard filters to fit these requirements leads to brittle code, security vulnerabilities, and maintenance nightmares.

The solution lies in Spring Security’s modular architecture. By implementing a Custom Authentication Provider, you can inject your specific business logic directly into the security lifecycle without compromising the framework’s integrity.

In this guide, we will build a production-ready Custom Authentication Provider using Spring Boot 3 and Spring Security 6. We will cover the architecture, implementation details, configuration, and critical edge cases you must handle.


Understanding the Architecture

Before writing code, it is crucial to understand where your custom logic fits. Spring Security uses a delegation model.

  1. AuthenticationFilter: Intercepts the request.
  2. AuthenticationManager: The interface defining how authentication is processed.
  3. ProviderManager: The standard implementation that iterates through a list of providers.
  4. AuthenticationProvider: The component that actually validates the user.
Continue reading Master Custom Authentication Providers in Spring Security 6

How to Check if a Number is a Pronic Number in Java

Whether you are preparing for a technical interview or exploring the fascinating world of number theory, encountering Pronic numbers is almost a rite of passage for Java developers. These numbers, often hidden in pattern-matching puzzles, have unique properties that make them a favorite for practicing algorithmic efficiency.

In this guide, we will dive deep into what Pronic numbers are and demonstrate two distinct ways to identify them using Java—ranging from a beginner-friendly loop to a high-performance mathematical “trick.”


What is a Pronic Number?

A Pronic number (also known as an oblong or rectangular number) is a number that is the product of two consecutive integers. Mathematically, a number P is pronic if it can be expressed as:

P = n X (n + 1)

For some integer n.

Examples of Pronic Numbers:

  • 0: 0 X 1 = 0
  • 2: 1 X 2 = 2
  • 6: 2 X 3 = 6
  • 12: 3 X 4 = 12
  • 20: 4 X 5 = 20
Continue reading How to Check if a Number is a Pronic Number in Java

Disarium Number in Java – Definition, Algorithm, and Complete Program

A Disarium number is a positive integer in which the sum of each digit raised to the power of its position (1-indexed from the left) equals the number itself. For example, 135 qualifies because 1¹ + 3² + 5³ = 1 + 9 + 125 = 135. In this tutorial you will learn exactly what makes a number Disarium, work through a manual verification, study a clean single-pass Java algorithm, and run a complete program that checks individual numbers and prints all Disarium numbers up to 100,000.

Continue reading Disarium Number in Java – Definition, Algorithm, and Complete Program

Complete Guide to Enabling HTTPS on Apache Tomcat

When your web application moves beyond hobby status, the first hardening step is wrapping every byte in TLS. Tomcat makes the process painless once you understand where the moving parts live. In this guide you will create (or import) a certificate, wire it into Tomcat’s connector, and verify that the padlock appears in every browser.


Why HTTPS on Tomcat Matters

Plain HTTP exposes cookies, credentials, and payloads to anyone on the wire. Search engines penalize insecure sites, browsers now flag non-TLS pages as “Not Secure”, and compliance frameworks such as PCI-DSS simply forbid clear-text traffic. Turning on HTTPS:

  • Encrypts data in transit
  • Proves server identity to clients
  • Unlocks HTTP/2 and modern protocols
  • Keeps Google and your security team happy

Prerequisites and Environment

Before touching configuration files ensure:

  • Tomcat 9.x or 10.x is installed and starts cleanly on port 8080
  • JAVA_HOME points to JDK 8+ (keytool comes with the JDK)
  • OpenSSL 1.1+ if you prefer generating private keys externally
  • Server DNS name (e.g. app.ankurm.com) resolves to the VM or container
Continue reading Complete Guide to Enabling HTTPS on Apache Tomcat

Log4j2 Logging Levels – Complete Guide

Imagine your application’s log file as a constant stream of information. In a production crisis, this stream becomes a firehose. How do you find the single critical error message in a flood of routine status updates? The answer lies in logging levels.

These aren’t just labels; they are the fundamental control mechanism in Log4j2. They allow developers to filter noise, pinpoint failures, and monitor application health effectively. Mastering this hierarchy is the key to creating logs that are helpful, not overwhelming. This guide explores Log4j2’s levels, from configuration to real-world best practices.


The Logging Threshold: How Levels Work

Think of logging levels as a gatekeeper’s volume knob. Each log message you write (an “event”) is assigned a level of importance, or severity. The logger itself is then configured with a threshold level.

When a message arrives, the framework compares its severity to the logger’s threshold. Only messages at or above the configured threshold are processed and sent to their destination (like a file or the console).

This simple mechanism provides fine-grained control over your application’s verbosity. You can run the exact same code in different environments and get drastically different log outputs—all without changing a single line of Java. In development, you might set the threshold low to see everything. In production, you set it high to capture only significant errors.

Continue reading Log4j2 Logging Levels – Complete Guide