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 user is 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 SecurityFilterChain and UserDetailsService beans.

What is the difference between a principal, credentials and authorities?

TermMeaningShopEase example
PrincipalWho the user is (usually a UserDetails or username)[email protected]
CredentialsThe proof of identity; erased after loginthe password or token
AuthoritiesPermissions 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?

  • WebSecurityConfigurerAdapter is removed: you declare a SecurityFilterChain bean.
  • authorizeRequests/antMatchers are replaced by authorizeHttpRequests/requestMatchers.
  • The lambda DSL is the standard style; .and() chaining is deprecated.
  • @EnableGlobalMethodSecurity is replaced by @EnableMethodSecurity.
  • Jakarta EE (jakarta.servlet) instead of javax.servlet; the security context must be saved explicitly in custom login code.