Spring Security and JWT Interview Questions for Java Developers (2026)
By Preeti Verma
Security questions are a favourite in backend interviews because they separate people who copied a login tutorial from people who understand it. You do not have to be a security expert, but you should be able to explain how a request is authenticated, where the token is checked, and what can go wrong.
Here are the questions that come up most for Java developers using Spring Boot, with the points a strong answer includes.
1. Authentication vs authorization
Authentication answers "who are you?" It checks credentials and identifies the user. Authorization answers "what are you allowed to do?" It runs after authentication and decides access to resources.
A simple example: logging in with a valid password is authentication. Being allowed to open the admin page only if you have the admin role is authorization. Many candidates mix them up, so a clean one-line difference is a quick win.
2. How does Spring Security work at a high level?
Spring Security is a chain of servlet filters that every request passes through before it reaches your controller. Each filter does one job: reading the session or token, checking credentials, handling CORS, protecting against CSRF, and deciding if the request is allowed.
Say that you configure it with a SecurityFilterChain bean (the older WebSecurityConfigurerAdapter is removed in current versions). A good answer also names the key pieces:
- SecurityContext: holds the current user's
Authenticationfor the request. - AuthenticationManager and AuthenticationProvider: check credentials.
- UserDetailsService: loads a user by username.
- PasswordEncoder: hashes and verifies passwords.
3. How should passwords be stored?
Never store plain text, and do not use a fast hash like plain MD5 or SHA-256. Use a slow, salted algorithm designed for passwords such as BCrypt (or Argon2), through a PasswordEncoder. Explain why slow is good: it makes brute-force guessing expensive. Adding a salt means two users with the same password get different hashes. Spring's BCryptPasswordEncoder handles the salt for you.
4. What is a JWT, and what is inside it?
A JSON Web Token has three parts, separated by dots: header, payload (claims such as user id, roles and expiry), and signature. Key points:
- It is signed, not encrypted. Anyone holding the token can read the payload, so never put secrets or sensitive data in it.
- The signature proves the token was issued by a party with the key and was not changed.
- It usually has an expiry claim (
exp).
A clear answer to "is a JWT secure?" is: it is tamper-evident, not secret, so it is only as safe as how you protect it in transit and storage.
5. Walk me through a JWT login flow
- The client sends the username and password to a login endpoint over HTTPS.
- The server verifies them (using the
AuthenticationManagerandPasswordEncoder). - On success, the server creates a signed JWT with the user id, roles and an expiry, and returns it.
- For later requests, the client sends the token in the
Authorization: Bearer <token>header. - A custom filter placed before the standard authentication filter reads the header, validates the signature and expiry, loads the user, and puts an
Authenticationinto theSecurityContext. - The request continues, and authorization rules decide if it is allowed.
If you can describe step 5 in your own words, you will stand out.
6. Why is the API stateless, and what does that mean?
Stateless means the server does not keep a session per user. Each request carries everything needed to authenticate it (the token). Benefits: easy horizontal scaling, because any instance can handle any request, and no shared session store. Cost: you cannot simply "log a user out" on the server, which leads to the next question.
7. How do you log a user out or revoke a token?
A pure JWT is valid until it expires. Options:
- Keep access tokens short-lived (minutes) and use a refresh token to get new ones.
- Store refresh tokens on the server so you can delete them on logout or if they are stolen.
- Keep a deny-list of revoked token ids if you need immediate revocation, at the cost of a lookup (which gives up some of the stateless benefit).
- Check the account state on each request when you need an immediate lock-out.
8. Access token vs refresh token
The access token is short-lived and sent with every API call. The refresh token is long-lived, used only to get a new access token, kept more securely, and sent only to the token endpoint. This limits the damage if an access token leaks.
9. Where should the client store the token?
There is a trade-off, and the honest answer is to say so:
- localStorage is easy but readable by any script on the page, so a cross-site scripting (XSS) bug can steal it.
- An
HttpOnly,Secure,SameSitecookie cannot be read by JavaScript, which protects against XSS theft, but a cookie-based design needs CSRF protection.
Either can be done safely, with strong input handling, a strict content security policy and short token lifetimes. Interviewers value that you see both sides.
10. What is CSRF, and why do many token APIs disable it?
Cross-site request forgery tricks a logged-in user's browser into sending a request the browser automatically authenticates, which happens with cookies. If your API authenticates only with a header token that the browser does not attach automatically, CSRF is not a risk in the same way, so stateless token APIs often disable it. If you use cookies for auth, keep CSRF protection on.
11. Roles vs authorities, and method security
Spring treats a role as an authority with the prefix ROLE_. hasRole("ADMIN") checks for ROLE_ADMIN; hasAuthority("ROLE_ADMIN") is the same thing written out. You can protect URLs in the filter chain, or protect methods with @PreAuthorize("hasRole('ADMIN')") once method security is enabled. Method-level checks are useful for business rules that URL patterns cannot express, such as "only the owner can edit this".
12. What is CORS, and is it the same as security?
CORS is a browser rule about which origins may call your API from JavaScript. It is not an authentication mechanism and does not protect against non-browser clients. Configure allowed origins explicitly, and avoid a wildcard together with credentials.
13. Common mistakes interviewers like to ask about
- Putting secrets or personal data inside a JWT.
- Using a weak or hard-coded signing key. Keep it in configuration, rotate it, and use a long random value.
- No expiry on tokens.
- Returning detailed error messages that help attackers ("user not found" vs "wrong password").
- Not rate limiting login attempts.
- Trusting a role sent from the client instead of the one in the verified token or the database.
Scenario questions to practise
- "A user's account was compromised. How do you cut off access immediately?"
- "A request arrives with an expired token. What should the API return, and how should the client react?" (A
401, then use the refresh token to get a new access token.) - "How would you secure an endpoint so a user can only read their own orders?"
Related reading: our guides on Spring Boot interview questions with scenarios and microservices interview questions for Java developers, where security often comes up in the same round.
Practise this on GenQuest
- Start a voice mock interview: answer out loud to an AI interviewer that knows your resume and the role, get follow-up questions, then read a scored report with a question-by-question review. Your first 15-minute interview is free.
- Ask the AI Coach: paste any question you are stuck on and get it explained in plain words, with a short answer you could say in an interview. See how it works in our AI Coach introduction.
- Open the question banks: Core Java scenarios, Blind 75 and NeetCode 150, high-level and low-level design questions, and company-wise sheets, with a free preview and progress tracking.
FAQ
Do I need OAuth2 for an interview? Know the basic idea: delegating login to a provider such as Google, and receiving tokens. Many interviews stay at the JWT and Spring Security level above.
Is JWT better than sessions? Neither is always better. Sessions are simple and easy to revoke. JWTs suit stateless APIs and many services. Say what you would choose for the case in front of you.
How deep do I need to go on cryptography? Know the difference between hashing, encryption and signing, and why passwords use a slow, salted hash. You rarely need the maths.
The takeaway
Explain the filter chain, the login flow and where the token is validated, then show you understand the trade-offs: stateless scaling versus revocation, and cookies versus local storage. Honest trade-offs are what a security interviewer wants to hear.