Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is Spring Security's SecurityContext and how is it propagated? स्प्रिंग सिक्योरिटी का SecurityContext क्या है और यह कैसे प्रोपेगेट होता है?

Answer

The SecurityContext holds the current Authentication object, representing the currently authenticated user, their credentials, and granted authorities. It's stored in a SecurityContextHolder, which by default uses a ThreadLocal so the context is available anywhere within the same thread handling a request, without needing to pass the user explicitly through every method call.

Because it's thread-local by default, the context does not automatically propagate to new threads spawned for async processing (@Async, a new Thread, or a thread pool); propagating it requires either passing the Authentication explicitly or switching the holder strategy to MODE_INHERITABLETHREADLOCAL.

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName();
Collection<? extends GrantedAuthority> roles = auth.getAuthorities();

SecurityContext वर्तमान Authentication ऑब्जेक्ट रखता है, जो वर्तमान में ऑथेंटिकेटेड यूज़र, उनके क्रेडेंशियल्स और स्वीकृत अथॉरिटीज़ को दर्शाता है। यह SecurityContextHolder में स्टोर होता है, जो डिफ़ॉल्ट रूप से ThreadLocal का उपयोग करता है ताकि कॉन्टेक्स्ट उसी थ्रेड के भीतर कहीं भी उपलब्ध हो।

डिफ़ॉल्ट रूप से थ्रेड-लोकल होने के कारण, कॉन्टेक्स्ट async प्रोसेसिंग के लिए बनाए गए नए थ्रेड्स में अपने आप प्रोपेगेट नहीं होता; इसे प्रोपेगेट करने के लिए Authentication को स्पष्ट रूप से पास करना या होल्डर स्ट्रैटेजी को MODE_INHERITABLETHREADLOCAL में बदलना पड़ता है।

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName();
Collection<? extends GrantedAuthority> roles = auth.getAuthorities();

Was this answer clear?