Q1. What is JWT?
JSON Web Token (JWT) is an open standard for securely transmitting information between parties as a JSON object. It's commonly used for authentication in REST APIs. A JWT consists of three parts: header, payload, and signature. It can be verified and trusted because it's digitally signed.
Q2. How do you implement JWT authentication in Spring?
Typically, you create a filter that intercepts requests, validates the JWT token, and sets the authentication in the security context. You'll need to add dependencies like jjwt. Configuration involves disabling CSRF, stateless session, and adding custom filter.
Q3. What is the structure of a JWT?
A JWT is a string of three base64url-encoded parts separated by dots: header.payload.signature. Header contains algorithm and type. Payload contains claims (e.g., user, roles, expiration). Signature verifies that the token hasn't been altered.
Q4. How do you secure REST endpoints with JWT?
Configure Spring Security to permit login endpoint, and require authentication for others. The JWT filter extracts token from Authorization header, validates it, and sets authentication. Then authorization rules (hasRole etc.) can be applied.
Q5. What are the advantages of JWT over session-based authentication?
JWT is stateless, so it scales better in distributed systems. The token contains all user information, so no server-side session storage is needed. It works well for microservices and mobile apps. However, token invalidation is harder than sessions.
