
7. Security Questions
This section focuses on Spring Security fundamentals, including authentication, authorization, JWT-based security, password protection, endpoint security, filters, and how modern Spring Boot applications secure REST APIs.
1. What is Spring Security?
Spring Security is a security framework for Java and Spring applications.
It provides features such as:
Authentication
Authorization
Password protection
Session management
CSRF protection
CORS handling
Security filters
JWT integration
Spring Security integrates deeply with Spring Boot and protects applications at multiple levels.
Without Spring Security, developers would need to manually implement:
Login systems
Role checks
Password hashing
Security filters
Access control
Session handling
Spring Security centralizes and standardizes these security concerns.
It is widely used in:
REST APIs
Enterprise systems
Banking systems
OAuth2 systems
Microservices
2. What is authentication?
Authentication is the process of verifying identity.
It answers:
“Who are you?”
Example:
Username + password login
JWT validation
OAuth login
API key verification
If credentials are valid:
User becomes authenticated
Security context stores user identity
Authentication happens before authorization.
3. What is authorization?
Authorization determines what an authenticated user is allowed to access.
It answers:
“What are you allowed to do?”
Example:
User | Access |
|---|---|
Admin | Can delete users |
Normal user | Cannot delete users |
Authorization usually checks:
Roles
Authorities
Permissions
4. Difference between authentication and authorization?
Authentication | Authorization |
|---|---|
Verifies identity | Verifies permissions |
“Who are you?” | “What can you do?” |
Happens first | Happens after authentication |
Login process | Access control process |
Example flow:
User logs in → authentication
User accesses admin endpoint → authorization
5. What is JWT?
JWT stands for JSON Web Token.
JWT is a compact token format commonly used for stateless authentication in REST APIs.
Instead of storing session data on server:
Server generates token
Client stores token
Client sends token with requests
JWT usually contains:
User identity
Roles
Expiration time
Claims
Example:
eyJhbGciOiJIUzI1Ni...JWT is digitally signed to prevent tampering.
6. What are the parts of JWT?
JWT contains three parts:
Header.Payload.SignatureSeparated by dots.
Header
Contains metadata.
Example:
{
"alg": "HS256",
"typ": "JWT"
}Payload
Contains claims/data.
Example:
{
"sub": "john",
"role": "ADMIN"
}Signature
Used to verify token integrity.
Generated using:
Secret key
RSA private key
Hashing algorithm
If payload changes, signature becomes invalid.
7. Where should JWT be stored?
Common options:
Storage | Notes |
|---|---|
HttpOnly Cookie | More secure |
LocalStorage | Simpler but vulnerable to XSS |
SessionStorage | Temporary storage |
Best practice for security-sensitive systems:
HttpOnly Secure Cookiebecause JavaScript cannot access HttpOnly cookies.
8. What is access token?
Access token is the main token used to access protected APIs.
Usually:
Short-lived
Sent with every request
Contains user identity and permissions
Example:
Authorization: Bearer <token>Access token expiration improves security.
9. What is refresh token?
Refresh token is used to generate new access tokens without requiring login again.
Usually:
Token Type | Lifetime |
|---|---|
Access Token | Short |
Refresh Token | Longer |
Flow:
Access token expires
Client sends refresh token
Server issues new access token
This improves both:
Security
User experience
10. How does JWT authentication work?
Typical JWT authentication flow:
User logs in
Server validates credentials
Server generates JWT
Client stores JWT
Client sends JWT in requests
Server validates JWT signature
User becomes authenticated
Example request:
Authorization: Bearer eyJhbGci...Spring Security usually processes JWT inside security filters.
11. What is password hashing?
Password hashing transforms passwords into irreversible encoded values.
Example:
password123becomes:
$2a$10$...Hashing protects passwords even if database leaks.
Good hashing algorithms:
BCrypt
Argon2
PBKDF2
12. Why should you not store plain text passwords?
Plain text passwords are extremely dangerous.
If database leaks:
All user passwords become exposed
Users may reuse passwords elsewhere
Massive security breach may occur
Proper systems always hash passwords before storage.
Example:
Never store:
password123Store only hashed value.
13. What is BCrypt?
BCrypt is a password hashing algorithm designed specifically for password security.
Features:
Salt generation
Slow hashing
Brute-force resistance
Example:
BCryptPasswordEncoder encoder =
new BCryptPasswordEncoder();BCrypt is intentionally computationally expensive to slow attackers.
Spring Security commonly uses BCrypt by default.
14. What is PasswordEncoder?
PasswordEncoder is Spring Security’s interface for password hashing.
Example:
PasswordEncoder encoder =
new BCryptPasswordEncoder();Common methods:
encode()
matches()Example:
encoder.matches(rawPassword, hashedPassword);Spring Security uses PasswordEncoder during authentication.
15. What is CSRF?
CSRF stands for Cross-Site Request Forgery.
It is an attack where a malicious website tricks a user into sending unwanted authenticated requests.
Example:
User logged into banking website
Malicious site triggers money transfer request automatically
Browser automatically includes cookies, causing security risk.
CSRF protection prevents this attack.
16. Is CSRF needed for stateless REST APIs?
Usually no.
Stateless REST APIs commonly use:
Authorization: Bearer JWTinstead of session cookies.
Since browser does not automatically attach JWT headers, CSRF risk becomes much lower.
Therefore many JWT-based APIs disable CSRF:
http.csrf(csrf -> csrf.disable());17. What is CORS?
CORS stands for Cross-Origin Resource Sharing.
Browsers block requests between different origins by default.
Example:
Frontend:
http://localhost:3000
Backend:
http://localhost:8080Different origins trigger browser security restrictions.
CORS allows backend to specify which origins are permitted.
18. How do you configure CORS in Spring Boot?
Example:
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000")
.allowedMethods("*");
}
};
}
}Spring Security may also require separate CORS configuration.
19. What is SecurityFilterChain?
SecurityFilterChain defines security rules for HTTP requests.
Modern Spring Security configuration:
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http)Inside this configuration developers define:
Authentication rules
Authorization rules
JWT filters
CSRF settings
CORS settings
Example:
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
);20. What is a security filter?
A security filter intercepts HTTP requests before controllers execute.
Spring Security internally uses many filters.
Examples:
JWT validation filter
Authentication filter
Authorization filter
CSRF filter
Flow:
Request
→ Security Filters
→ ControllerFilters decide whether request should continue or be rejected.
21. How do you protect endpoints by role?
Example:
.requestMatchers("/admin/**")
.hasRole("ADMIN")Only authenticated users with ADMIN role can access.
Spring Security checks user authorities internally.
22. What is @PreAuthorize?
@PreAuthorize performs method-level authorization.
Example:
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser() {
}Spring evaluates expression before method execution.
Useful for fine-grained security control.
23. Difference between role and authority?
Roles are higher-level concepts.
Authorities are lower-level permissions.
Example:
Role | Authorities |
|---|---|
ADMIN | READ, WRITE, DELETE |
USER | READ |
Internally Spring Security stores both as authorities.
Convention:
ROLE_ADMIN
ROLE_USERare treated as roles.
24. What status code for unauthenticated request?
Usually:
401 UnauthorizedMeaning:
User is not authenticated
Login/token required
Example:
Missing JWT
Invalid credentials
25. What status code for unauthorized access?
Usually:
403 ForbiddenMeaning:
User is authenticated
But lacks required permissions
Example:
USER role accessing ADMIN endpoint
