Lessons available in both languages
Java Backend · Interview Prep

Spring Security interview questions & answers

204+ real Spring Security interview questions with model answers, plus free lessons to learn the concepts. Prepare in English & Hinglish, then practise with an AI mock interview.

18 topics · 204+ questions

Hirenix kaise padhata hai

Ek chapter. 90 minute.
Interview ke liye taiyaar.

Har concept ek real-world problem se — jaisa production code mein aata hai, waisa. Ratna nahi padta, samajh aa jaata hai. Har question ka model answer diya hai: interviewer ko exactly kya bolna hai, aur kyun. Phir usi chapter ka AI mock interview.

  • 📖Concept, 5 min meinJargon nahi — seedhi baat
  • 🛠️Real-world problemJaisa production code mein aata hai
  • 💬Model answerInterview mein kya bolna hai
  • 🧠FlashcardsRevision 10 min mein
  • 🤖AI mock interviewFollow-up bhi poochta hai
  • 📊Weak topicsKahan phans rahe ho, pata chale
Ye chapter shuru karo — free🌐 English🇮🇳 Hinglish
A student learning an interview concept on Hirenix at home
Video playlistsyllabus ke hisaab se18h+
Hirenix chapterinterview ke hisaab se90 min

Farq content ka nahi, filter ka hai — sirf wahi jo production mein actually use hota hai aur interview mein actually poocha jaata hai. Kitaabi topics jo industry mein kahin nahi chalte, wo yahan nahi milenge.

Lessons available in both languages

What you’ll learn

  • Spring Security kyun: config likhne se pehle hi kya mil jaata hai
  • Security filter chain aur uska kram
  • Authentication vs authorization: 401 vs 403Free account
  • UserDetailsService aur authentication providersFree account
  • Password storage: BCrypt aur encoder ka prefixFree account
  • Requests ko authorize karna: matchers, rules, aur kram kyun maayne rakhta haiFree account
  • Roles vs authorities aur ROLE_ prefixFree account
  • Method security: PreAuthorize aur wo annotation jo kuch nahi kartaFree account
  • SecurityContextHolder aur current user kaise milta haiFree account
  • CSRF protection: default me ON, aur kab band karna sahi haiFree account
  • Sessions vs stateless APIsFree account
  • JWT aur resource server: valid, expired, tamperedFree account
  • CORS aur security headersFree account
  • Custom filters, entry points aur access-denied handlingFree account
  • RecapFree account
  • Project: Job Board API ko Secure Karo
  • Project: JWT Login FlowFree account
  • Project: Role-Based Admin AreaFree account

Spring Security kyun: config likhne se pehle hi kya mil jaata hai

Spring Security kis liye hai, ye samajhne ka sabse tez tareeka hai — kuch bhi add mat kijiye, aur dekhiye hota kya hai.

Neeche wala demo ek poora application hai: ek @SpringBootApplication class, aur ek @GetMapping("/hello") jo ek string lautata hai. Isme koi security configuration nahi hai — na config class, na annotation, na filter. Sirf ek cheez badli hai: Spring Security ki jars classpath par hain.

Output hi poora sabak hai. Bina credentials ke endpoint 401 deta hai. Sahi username-password par 200. Sahi username par galat password dene par phir se 401. Ye bartaav developer ne likha hi nahi hai.

Asal me ON kya hua

Startup par teen alag cheezein hui, aur teenon ka naam interviewer aapse sunna chahta hai:

  1. springSecurityFilterChain naam ka ek bean ban gaya. Har secured request usi se guzarti hai — agla topic use khol kar dekhta hai.
  2. Ek in-memory user ban gaya. Aam taur par Boot ek random password banata hai aur use log me chhapta hai; demo ne spring.security.user.* se username-password pin kar diya hai taaki test dobara wahi nateeja de.
  3. HTTP Basic authentication chalu ho gaya — isiliye koi browser ya HTTP client credentials bhej hi paata hai.

Output me bean ki ginti is poore kaam ka size dikhati hai: 206 beans, us application me jiska source do method ka hai. Boot ne ye beans isliye register ki kyunki Security ki classes classpath par hain — wahi @ConditionalOnClass wala mechanism jo Spring Boot chapter me naapa gaya tha. Boot ke apne numbers isi ki tasdeeq karte hain: ek saade web app par ginti 156 thi, aur sirf Security ki jars jodte hi 286 ho gayi.

Authentication aur authorization do alag sawaal hain. Authentication poochta hai aap kaun hain aur ek Authentication object banata hai. Authorization poochta hai aapko ijaazat hai ya nahi aur haan/naa deta hai. Is chapter ke lagbhag saare bharmane wale nateeje galat sawaal ka jawab dene se aate hain — 401-vs-403 wala topic poora isi par hai.

Khud filter likhne ke bajay framework kyun

Header check karne wala apna filter likhna pachaas line ka kaam lagta hai, aur happy path ke liye hai bhi. Pachaas line me jo nahi aata wo hai uske aas-paas ki har cheez: password hashing aur baad me algorithm upgrade karna, ye leak na hone dena ki username exist karta hai ya nahi, cookie wale flows ke liye CSRF, session fixation, default security headers, aur sahi mauke par sahi status code lautana. Inme se har ek is chapter ka apna topic hai, aur har ek Spring Security pehle se karti hai.

Kab use karein: har us Spring application me jisme users, roles, tokens ya admin area hai — yaani lagbhag har wo backend jo job description me likha hota hai. Interview me bhi jawab yahi expected hai: "maine filter likha tha" nahi, balki "maine SecurityFilterChain configure ki thi".

Trade-off kya hai: keemat ye hai ki defaults dikhte nahi. Aapke source me kahin nahi likha ki endpoint protected hai, aur kahin nahi likha ki CSRF ON hai. Isiliye ye chapter batata nahi, naapta hai — aur agla topic baat karne ke bajay seedha filter chain chhapta hai.

Configuration ka aaj ka roop HttpSecurity se bana hua SecurityFilterChain bean hai. Agar koi purana tutorial WebSecurityConfigurerAdapter extend karta dikhe, to wo class Spring Security 6 me hai hi nahi — ye bata dena khud ek aam interview checkpoint hai.

// ---- smoke/Smoke.java ----
package smoke;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class Smoke {

  @GetMapping("/hello")
  public String hello() { return "hello"; }

  // NOTE: there is no security configuration anywhere in this file.

  public static void main(String[] args) throws Exception {
    System.setProperty("server.port", "0");
    // Boot generates a random password and logs it. Pinned here so the test repeats.
    System.setProperty("spring.security.user.name", "waquar");
    System.setProperty("spring.security.user.password", "s3cret");

    try (ConfigurableApplicationContext ctx = SpringApplication.run(Smoke.class, args)) {
      int port = Integer.parseInt(ctx.getEnvironment().getProperty("local.server.port", "0"));

      // status(port, path, basicCredentials) does one real HTTP call
      System.out.println("  /hello  no creds        -> " + status(port, "/hello", null));
      System.out.println("  /hello  waquar:s3cret   -> " + status(port, "/hello", "waquar:s3cret"));
      System.out.println("  /hello  waquar:wrong    -> " + status(port, "/hello", "waquar:wrong"));

      System.out.println("  springSecurityFilterChain bean present = "
          + ctx.containsBean("springSecurityFilterChain"));
      System.out.println("  total beans = " + ctx.getBeanDefinitionCount());
    }
  }
}

Security filter chain aur uska kram

Spring Security aapke controller ke andar ki koi layer nahi hai. Wo servlet filters ki ek chain hai jo aapke controller se pehle chalti hai — aur is chapter ke lagbhag saare chaunkane wale nateeje isi ek vaakya se samajh aate hain.

Request ka raasta teen naam wale hisson se guzarta hai, aur interviewer inhe isi kram me sunna chahta hai:

  1. DelegatingFilterProxy — ek saadha servlet filter jo servlet container me register hota hai. Container ko Spring beans ka kuch pata nahi hota, isliye ye proxy pul ka kaam karta hai: wo ek Spring bean dhoondh kar usse kaam karwata hai.
  2. FilterChainProxy — wahi bean. Uske paas SecurityFilterChain objects ki list hoti hai aur wo pehli aisi chain chunta hai jiska matcher request se milta hai.
  3. SecurityFilterChain — ek chain: ek matcher aur filters ki ek kram wali list, jo asal me kaam karti hai.

Demo ye sab batata nahi, chhapta hai. Usme do chain declare ki gayi hain — ek /api/** ke liye, ek baaki sabke liye — phir FilterChainProxy.getFilterChains() par chal kar har filter ka class naam chhapa gaya hai.

Dono chains ko saath me padhiye

Donon chains me 11 filter hain, par wo ek jaise 11 nahi hain — aur yahi poori baat hai:

  • /api/** wali chain me BasicAuthenticationFilter hai aur CsrfFilter nahi, kyunki usme httpBasic() aur csrf().disable() likha tha.
  • Catch-all chain me CsrfFilter hai aur BasicAuthenticationFilter nahi, kyunki usme dono me se kuch nahi likha tha.

Yaani filter ki list koi tay cheez nahi hai jo rat li jaaye. Wo aapki configuration se banti hai, aur is chapter ne ab teen alag configurations me teen alag gintiyan naap li hain: HTTP Basic ke saath aur CSRF chalu rehne par 12, upar wali dono chains par 11-11, aur custom filter jodne + CSRF band karne par phir se 11. Inme se kisi ek ko "Spring Security me itne filter hote hain" kehna galat hai — isliye nahi ki number galat hai, balki isliye ki sawaal ka koi tay jawab hai hi nahi. "Us config par 11 bane the, aur maine unhe aise chhapa tha" wo jawab hai jo bana kar nahi bola ja sakta.

Kram wala hissa hi kaatta hai

Dono chains me kram sthir hai aur seekhne laayak hai:

DisableEncodeUrl -> WebAsyncManagerIntegration -> SecurityContextHolder -> HeaderWriter -> (Csrf) -> Logout -> (BasicAuthentication) -> RequestCacheAware -> SecurityContextHolderAwareRequest -> AnonymousAuthentication -> ExceptionTranslation -> Authorization

Is list se teen baatein seedhi nikalti hain:

  • CsrfFilter BasicAuthenticationFilter se pehle chalta hai. Koi request credentials jaanche jaane se pehle hi CSRF par reject ho sakti hai, isliye sahi credentials bina token wale POST ko nahi bachate. Client tak phir kaunsa status pahunchta hai wo alag sawaal hai — CSRF wala topic ek aisa 401 naapta hai jo asal me protected /error page ka CsrfFilter ke 403 par diya gaya jawab hai, is kram ka nateeja nahi.
  • AuthorizationFilter sabse aakhir me hai. Authorization tabhi chal sakta hai jab identity maujood ho — isiliye role check pehla nahi, aakhri darwaza hota hai.
  • ExceptionTranslationFilter usse thoda pehle baitha hai. Wahi apne baad wali har cheez ke liye AuthenticationException ko 401 aur AccessDeniedException ko 403 banata hai. Jo filters pehle chalte hain wo apna status khud likhte hain — CsrfFilter token na hone par us tak pahunche bina hi 403 deta hai.

Ek se zyada chain kab: jab ek hi application stateless JSON API aur browser UI dono deti ho. API wali chain ko securityMatcher("/api/**") dijiye, CSRF band aur token authentication ke saath; doosri chain browser wala hissa sambhale, CSRF ON aur form login ke saath. @Order tay karta hai kaunsi pehle dekhi jaayegi, aur pehla match hi jeetta hai — catch-all chain pehle rakh di to wo har request nigal legi aur specific chain kabhi chalegi hi nahi.

Trade-off kya hai: filter saste hain par muft nahi, aur usse badi baat — wo aapke source me dikhte nahi. Kyunki security dispatcher servlet se pehle chalti hai, security ka failure aapke controller tak pahunchta hi nahi — matlab @ControllerAdvice aur ProblemDetail 401 ya 403 ka roop nahi badalte. Un responses ko apne hisaab se banane ke liye AuthenticationEntryPoint ya AccessDeniedHandler chahiye, jo isi chapter ka aage wala topic hai.

// ---- t2/T2.java ----
package t2;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.Filter;

@SpringBootApplication
@RestController
public class T2 {
  @GetMapping("/api/data") public String api() { return "data"; }
  @GetMapping("/page")     public String page() { return "page"; }

  @Bean @Order(1)                       // first chain: only /api/**
  SecurityFilterChain apiChain(HttpSecurity http) throws Exception {
    return http.securityMatcher("/api/**")
        .csrf(c -> c.disable())
        .authorizeHttpRequests(a -> a.anyRequest().authenticated())
        .httpBasic(b -> {})
        .build();
  }

  @Bean @Order(2)                       // second chain: everything else
  SecurityFilterChain webChain(HttpSecurity http) throws Exception {
    return http.authorizeHttpRequests(a -> a.anyRequest().permitAll()).build();
  }

  public static void main(String[] args) {
    System.setProperty("server.port", "0");
    try (ConfigurableApplicationContext ctx = SpringApplication.run(T2.class, args)) {
      FilterChainProxy proxy = ctx.getBean("springSecurityFilterChain", FilterChainProxy.class);
      System.out.println("total chains = " + proxy.getFilterChains().size());
      int i = 0;
      for (var chain : proxy.getFilterChains()) {
        System.out.println("chain[" + i + "] filters=" + chain.getFilters().size());
        for (Filter f : chain.getFilters()) System.out.println("    " + f.getClass().getSimpleName());
        i++;
      }
    }
  }
}

Project: Job Board API ko Secure Karo

Ye chapter ka entry project hai, aur ye jaan-boojh kar koi nayi application nahi hai. Spring Data JPA chapter ne ek job board banaya tha — companies, jobs, paging ke saath search, job band karna — aur uspar koi authentication tha hi nahi. Jo bhi us API tak pahunch sakta tha wo job post kar sakta tha ya kisi aur ki job band kar sakta tha. Ye project uspar taala lagata hai.

Interview bhi isi kram me poochta hai: aapne API banayi, database joda, secure kaise kiya?

Pichhle chapter se ek imaandaar farak

JPA chapter bina web layer ke chala tha; is chapter me web layer hai aur database nahi hai. Isliye yahan entities JPA entities ke bajay ek Map me pade record hain. Security par iska koi asar nahi — filter chain ko pata hi nahi hota ki controller ke peechhe kya hai — par is file ko persistence wale kaam ka vikalp mat samajhiye. Dono halves jaan-boojh kar un chapters me padhaye gaye hain jo unhe sach me chala sakte hain.

Rules, aur har ek ka aakaar aisa kyun hai

.requestMatchers(HttpMethod.GET,    "/api/jobs").permitAll()
.requestMatchers(HttpMethod.POST,   "/api/jobs").hasRole("RECRUITER")
.requestMatchers(HttpMethod.DELETE, "/api/jobs/**").hasRole("ADMIN")
.anyRequest().authenticated()

Matchers method-aware hain. GET /api/jobs aur POST /api/jobs ek hi path hain par do bilkul alag permissions ke saath, jo asli API me aam baat hai — job feed padhna public hai, usme chhapna nahi. Sirf path wala matcher ye keh hi nahi sakta.

Kram specific se general hai. Har rule apne baad wale se sankra hai, aur anyRequest() sabse aakhir me hai. Ulta likhne par application start hi nahi hoti — authorizing-requests wala topic use naapta hai.

Aakhri line ek whitelist hai. anyRequest().authenticated() ka matlab hai ki /api/jobs/mine, jiska kisi rule me zikr tak nahi, anonymous callers ke liye default me band hai. Agle mahine koi /api/jobs/{id}/applicants jodega aur security config bhool jaayega, to wo bhi band hi rahega. authenticated() par khatam karne ka poora tark yahi hai.

csrf.disable() aur STATELESS yahan sahi hain, aur sirf credential ki wajah se: HTTP Basic ek aise header me aata hai jise browser khud kabhi nahi jodta. Credential ko cookie me le jaaiye aur dono faisle galat ho jaate hain.

Run kya sabit karta hai

GET    /api/jobs        anonymous -> 200  []
POST   /api/jobs        anonymous -> 401
POST   /api/jobs        asha USER -> 403
POST   /api/jobs        rec  REC  -> 200  {"id":1,...,"postedBy":"rec"...}
GET    /api/jobs/mine   rec  REC  -> 200  [ {"id":1,...} ]
GET    /api/jobs/mine   asha USER -> 200  []
DELETE /api/jobs/1      rec  REC  -> 403
DELETE /api/jobs/1      boss ADM  -> 200  deleted

Doosri aur teesri row ko saath padhiye — poora 401-banaam-403 wala sabak usi shakal me hai jisme wo asal me milta hai. Wahi POST, do baar mana, do alag wajahon se: koi nahi ko 401, galat koi ko 403.

Aur paanchvi-chhathi row: wahi endpoint, wahi status, alag data. /api/jobs/mine ko kisi rule ne bachaya hi nahi — use controller bachata hai, Authentication.getName() se filter karke. Ye farak maayne rakhta hai: authorization ke rules tay karte hain ki aap kisi cheez ko bula sakte hain ya nahi; ye ki aapko kaunsi rows dikhengi, wo sirf aapka code tay kar sakta hai. Koi rule kabhi "aapki apni jobs" nahi keh sakta.

Khud banaiye

  1. Teen users BCrypt se encode kiye hue passwords ke saath — ek candidate, ek recruiter, ek admin. Demo ke bahar {noop} kabhi nahi.
  2. Upar wale chaar rules. Har ek ko do taraf se jaanchiye: wo role jise pass hona chahiye, aur wo jise nahi.
  3. GET /api/jobs/mine ko Authentication.getName() se filter kijiye.
  4. Phir jaan-boojh kar todiye aur dekhiye: hasRole("RECRUITER") ko hasAuthority("RECRUITER") kar dijiye aur har post 403 se fail hogi, kyunki stored authority ROLE_RECRUITER hai.

Ye dhaancha kab: har us API me jisme reads public hain aur writes adhikaar wale — yaani zyadatar API. Chain par mote rules, code me row-level faisle.

Kab NAHI: ownership ko authorizeHttpRequests me likhne ki koshish mat kijiye. "Jis recruiter ne ye job post ki sirf wahi use band kar sakta hai" URL ka rule hai hi nahi — wo ya to argument ke saath @PreAuthorize hai, ya service me ek check. Matchers ko ownership ke rules me morna aisi configuration banata hai jise koi padh nahi sakta aur aise chhed jo kisi ko dikhte nahi.

Trade-off kya hai: ye rules theek isliye padhne laayak hain kyunki mote hain, aur mote rules us service method ko nahi bacha sakte jo kisi scheduled job ya doosre controller se pahuncha jaaye. Yahi gap agle do projects aur method-security wala topic bharte hain.

// ---- p16/P16.java ----
// Ch9 ka Job - bina JPA ke, kyunki is chapter ke env me koi DB nahi hai.
record Job(Long id, String title, String city, String postedBy, String status) {}

@GetMapping("/api/jobs")                                   // public feed
public Collection<Job> feed() { return JOBS.values(); }

@PostMapping("/api/jobs")                                  // recruiter only
public Job post(@RequestParam String title, @RequestParam String city, Authentication a) {
  long id = SEQ.incrementAndGet();
  Job j = new Job(id, title, city, a.getName(), "OPEN");   // owner = the caller
  JOBS.put(id, j);
  return j;
}

@GetMapping("/api/jobs/mine")                              // any logged-in user
public List<Job> mine(Authentication a) {
  return JOBS.values().stream().filter(j -> j.postedBy().equals(a.getName())).toList();
}

@DeleteMapping("/api/jobs/{id}")                           // admin only
public String delete(@PathVariable Long id) {
  return JOBS.remove(id) == null ? "not-found" : "deleted";
}

@Bean
SecurityFilterChain chain(HttpSecurity h) throws Exception {
  return h
      .csrf(c -> c.disable())                              // credential is a header, not a cookie
      .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
      .authorizeHttpRequests(a -> a
          .requestMatchers(HttpMethod.GET,    "/api/jobs").permitAll()
          .requestMatchers(HttpMethod.POST,   "/api/jobs").hasRole("RECRUITER")
          .requestMatchers(HttpMethod.DELETE, "/api/jobs/**").hasRole("ADMIN")
          .anyRequest().authenticated())                   // whitelist default
      .httpBasic(b -> {})
      .build();
}

@Bean PasswordEncoder enc() { return new BCryptPasswordEncoder(); }

@Bean UserDetailsService users(PasswordEncoder e) {
  return new InMemoryUserDetailsManager(
      User.withUsername("asha").password(e.encode("pw1")).roles("USER").build(),
      User.withUsername("rec").password(e.encode("pw2")).roles("RECRUITER").build(),
      User.withUsername("boss").password(e.encode("pw3")).roles("ADMIN").build());
}

Spring Securityinterview questions & answers

10 sample questions below — 204+ in the full bank inside.

csrf(c -> c.disable()) ke baad us POST ka kya hota hai jo pehle fail ho raha tha?

Wo baaki requests jaisa bartaav karta hai: bina credentials ke 401 aur sahi credentials ke saath 200 - theek isi tarah naapa gaya. CSRF ka check chain se bas hat jaata hai, isliye nateeja tay karne wali cheezein sirf authentication aur phir authorization reh jaati hain. Yahi tulna sabse saaf tareeke se dikhati hai ki pehle wala 401 CSRF se aaya tha, credentials se nahi, kyunki dono runs ke beech credentials badle hi nahi. Isse ye bhi dikhta hai ki CSRF band karne se authentication kamzor nahi hota - wo cross-site nakli writes ke khilaaf ek khaas bachav hataata hai, aur kuch nahi.

In simple terms: Theek ek cheez badal kar dobara naapna hi 'mujhe lagta hai CSRF tha' ko jaan-ne me badal deta hai, aur ye bhi baandh deta hai ki band karne ki asli keemat kya hai.

JWT ke teen hisse kaunse hain, aur kya payload raaz hota hai?

header.payload.signature, dot se judi teen base64url segments. Header signing algorithm ka naam leta hai, payload sub, exp aur scope jaise claims le kar chalta hai, aur signature pehle do par ek key se banta hai. Payload encode hota hai, encrypt nahi - jiske paas bhi token hai wo bina kisi key ke har claim decode karke padh sakta hai, jise demo decode kiya hua payload chhaap kar dikhata hai. Do niyam nikalte hain: JWT me kabhi koi raaz mat daaliye, aur bina verify kiye token par kabhi bharosa mat kijiye, kyunki decode karna verify karna nahi hai. Signature se chhed-chhaad ka pata chalta hai, gopneeyata nahi milti.

In simple terms: Encoded-banaam-encrypted ka farak JWT ki sabse bhaari galatfehmi hai, aur wahi tay karta hai ki token me kya daala ja sakta hai.

CORS kab configure karna padta hai, aur kab wo bemaani hai?

Tab configure kijiye jab browser front end API se alag origin par serve hota ho - alag domain, alag port, ya http banaam https. localhost:3000 par chalta single-page app jo localhost:8080 ki API bulata hai, wo pehle se alag origin hai - isiliye lagbhag har local development setup isse takrata hai. Wo server-to-server calls, mobile apps ya kisi bhi non-browser cheez ke liye bemaani hai, kyunki wahan niyam laagu karne wala browser hai hi nahi - non-browser problem ko 'theek' karne ke liye dheeli policy jodna sirf ye badha deta hai ki browsers ko kya karne ki ijaazat hai, aur theek kuch nahi karta.

In simple terms: Port ka alag origin hona local par logon ko pakadta hai, aur 'non-browsers ke liye bemaani' wala aadha hissa ek khatarnaak nakal-wala fix rok deta hai.

Kya CSRF protection default me chalu hai, aur chalti hui application par aap ise kaise confirm karenge?

Haan - jis chain me CSRF ka zikr tak nahi, uspar wo chalu hai. Naape gaye demo ki SecurityFilterChain na csrf(...) bulati hai na disable(), aur bina token wala POST reject ho gaya. Chalti hui application par confirm kijiye FilterChainProxy se chain chhaap kar aur list me CsrfFilter dhoondh kar: maujood matlab chalu, gayab matlab kisi ne band kiya. Ye configuration padhne se behtar hai, kyunki configuration me sirf wo darj hai jo aapne badla - kisi bhi csrf line ka na hona matlab default, aur default chalu hai.

In simple terms: 'Na hona matlab chalu' wala ulta niyam hi CSRF ko chaunkane wala banata hai, aur filter list chhaap dena use bina bahas ke hal kar deta hai.

Authentication object me kya hota hai, aur application code me aap asal me kaunsa hissa use karte hain?

Usme principal (kaun), credentials (aksar authentication ke baad saaf kar diye jaate hain), authorities (wo kya kar sakta hai) aur ek isAuthenticated flag hota hai. Application code me lagbhag hamesha aapko username ke liye getName() aur permission check ke liye getAuthorities() chahiye hote hain, kyunki dono har mechanism ke liye parifashit hain. getPrincipal() ka type har mechanism me alag hota hai - form login aur Basic par UserDetails, resource server chain par Jwt, aur anonymous par saadi string anonymousUser - isliye use cast karne wali line tabhi tootti hai jab doosra authentication mechanism juda.

In simple terms: Typed-principal wala jaal asli aur aam hai, aur uska surakshit vikalp (getName) ek shabd ka badlaav hai jiske baare me zyadatar logon ko bataya hi nahi gaya.

Agar custom filter chain.doFilter(req, res) bulana bhool jaaye to kya hota hai?

Request chain ke beech me hi ruk jaati hai. Controller kabhi nahi chalta, baaki filters kabhi nahi chalte, aur client ko aam taur par bina kisi safai ke khaali 200 milta hai - aisa response jo error ke bajay ye lagta hai ki endpoint ne kuch lautaya hi nahi. Ye classic filter bug theek isliye hai ki kuch phenkta hi nahi. Niyam ye hai: jo filter sirf dekhta ya jodta hai use request hamesha aage badhani chahiye, aur jo filter reject karna chahta hai use status likh kar aur return karke saaf taur par karna chahiye, taaki mansha dikhe, kisi chhooti hui line se anumaan na lagana pade.

In simple terms: Khaali 200 ek anootha bharmane wala lakshan hai kyunki wo failure jaisa lagta hi nahi, aur wajah galat line nahi balki ek chhooti hui line hoti hai.

Ek application, ek endpoint family, teen callers. Status codes ka anumaan lagaiye aur bataiye har ek waisa kyun hai.

/public/** permitAll, /admin/** hasRole ADMIN aur baaki sab authenticated hone par: /public/ping anonymous par 200, kyunki rule use jaane deta hai; /user/me anonymous par 401, kyunki koi identity bani hi nahi; /user/me ROLE_USER se 200; /admin/panel usi ROLE_USER se 403, kyunki identity pata hai aur role nahi hai; aur /admin/panel ROLE_ADMIN se 200. Doosri aur chauthi row hi sabak hain: ek hi endpoint family do baar mana hui, ek baar ye na jaan-ne par ki aap kaun hain, aur ek baar theek-theek jaan-ne par.

In simple terms: Bina chalaye paanchon ka anumaan laga pana sabse saaf saboot hai ki candidate ke dimaag me dono sawaal alag hain.

Aam authorization rules ke naam bataiye aur har ek ka kaam, un me se ek aisa bhi jo logon ko chaunkata hai.

permitAll() hamesha jaane deta hai; authenticated() koi bhi identity maangta hai; hasRole("ADMIN") ROLE_ADMIN authority maangta hai; hasAuthority("SCOPE_read") bilkul wahi authority string maangta hai; hasAnyRole(...) aur hasAnyAuthority(...) list lete hain; aur denyAll() sabko mana kar deta hai. Chaunkane wala denyAll() hai - wo administrator ko bhi mana karta hai, jiski tasdeeq naapa gaya run ROLE_ADMIN caller ko 403 de kar karta hai. Isi se wo us endpoint ke liye kaam ka ban jaata hai jo maujood to hai par HTTP se kabhi pahunchna nahi chahiye, na ki hasRole ke ek sakht version ki tarah.

In simple terms: denyAll ko aksar 'normal users ko mana karo' samajh liya jaata hai, aur admin ko mila 403 sabse tez sudhaar hai.

CSRF kya hai, aur browser ka kaunsa bartaav use mumkin banata hai?

Cross-Site Request Forgery: attacker ka page aapke browser se us site par state badalne wali request bhijwa deta hai jispar aap logged in hain, aur browser aapki cookies khud jod deta hai, chahe request kisi bhi site ne karwayi ho. To evil.example ka ek form bank.example/transfer par POST kar sakta hai aur bank ko ek poori tarah authenticated request dikhti hai. Attacker response padhta hi nahi aur use zaroorat bhi nahi - nuksan to write me ho chuka. Browser ka wahi ek bartaav, cookie ka apne aap judna, poore hamle ka aadhaar hai aur isliye is baat ka bhi aadhaar hai ki bachav kab chahiye.

In simple terms: Hamle ko cookie ke apne aap judne se baandh dena hi aage ke 'ise band kab kar sakte hain' wale sawaal ko mool siddhant se hal karne laayak banata hai.

Bahar se aap kaise sabit karenge ki JWT se surakshit API sach me stateless hai?

Ek safal authenticated response par Set-Cookie dekhiye. Naape gaye run me wo khaali tha - koi JSESSIONID nahi, kuch nahi - yaani server ne dono requests ke beech kuch store nahi kiya aur koi bhi instance koi bhi request le sakta tha. Agar jis API ko aap stateless maan rahe hain uspar JSESSIONID dikhe, to kisi ne wo session banayi jo aapki mansha nahi thi, aur aam wajahein hain: kahin pada hua request.getSession(), default policy par chhodi gayi chain, ya NEVER policy ka pehle se maujood browser session utha lena. Ye ek header ka check hai jiske liye code tak pahunch chahiye hi nahi.

In simple terms: Bahar se, bina code ke saboot isliye keemti hai ki wo kisi aur ki service par bhi chalta hai aur us environment me bhi jahan aap debug nahi kar sakte.

194+ more Spring Security questions inside

Create a free account to read the full question bank, learn every topic, and practise with an AI mock interview.

Unlock all questions — free

Ready to practise Spring Security?

Unlock every topic free, then face an AI interviewer that asks follow-ups and grades your answers.