Basic Interview Questions
What is the difference between authentication and authorization?
Authentication answers "who are you?" (checking a username/password, a token or a Google login). Authorization answers "what are you allowed to do?" (can this user delete a product?). Authentication always comes first. In HTTP terms, a failed authentication returns 401 Unauthorized and a failed authorization returns 403 Forbidden.
What is Spring Security and why use it instead of writing your own checks?
Spring Security is the standard framework for authentication, authorization and protection against common attacks in Spring applications. It gives you a tested filter chain, password hashing, session and token support, OAuth2/OIDC login, method-level security and CSRF/CORS/security-header handling. Hand-written checks in controllers are easy to forget on one endpoint and usually miss things like timing attacks, session fixation or CSRF.
What happens when you add spring-boot-starter-security to a Spring Boot app?
- Every endpoint now needs authentication (secure by default).
- A default user named
useris created, with a random password printed in the log:Using generated security password: 8e55... - A form login page (
/login), HTTP Basic, logout (/logout), CSRF protection and security headers are enabled. - You override all of this by declaring your own
SecurityFilterChainandUserDetailsServicebeans.
What is the difference between a principal, credentials and authorities?
| Term | Meaning | ShopEase example |
|---|---|---|
| Principal | Who the user is (usually a UserDetails or username) | [email protected] |
| Credentials | The proof of identity; erased after login | the password or token |
| Authorities | Permissions granted to the user (GrantedAuthority) | ROLE_ADMIN, product:write |
All three live inside the Authentication object stored in the SecurityContext.
How do you get the currently logged-in user in a controller?
@GetMapping("/api/me")
public Map<String, Object> me(@AuthenticationPrincipal UserDetails user) {
return Map.of("username", user.getUsername(), "roles", user.getAuthorities());
}
// Anywhere else (service layer):
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName();For a JWT resource server, use @AuthenticationPrincipal Jwt jwt instead.
What changed in Spring Security 6 compared to 5?
WebSecurityConfigurerAdapteris removed: you declare aSecurityFilterChainbean.authorizeRequests/antMatchersare replaced byauthorizeHttpRequests/requestMatchers.- The lambda DSL is the standard style;
.and()chaining is deprecated. @EnableGlobalMethodSecurityis replaced by@EnableMethodSecurity.- Jakarta EE (
jakarta.servlet) instead ofjavax.servlet; the security context must be saved explicitly in custom login code.