Authentication
Authentication answers who are you?.
Introduction
Authentication answers who are you?. The caller presents credentials — password, bearer JWT, or an OAuth2 token — and Spring Security builds an Authentication object stored in the SecurityContext.
For password-based Orders login, you implement UserDetailsService (or a custom AuthenticationProvider), hash with PasswordEncoder, and let AuthenticationManager verify. For APIs, login often returns tokens; subsequent requests authenticate via the Authorization header.
Authentication is not authorization. A valid login only proves identity. Whether that user may cancel another customer's order is a later check.
This lesson wires identity for TechLearningPRO Orders using Boot 3 packages (jakarta.* where applicable) and Security 6 APIs.
Purpose of this lesson
Prove caller identity into the SecurityContext using UserDetailsService, PasswordEncoder, and the authentication manager flow.
Understanding the topic
Credentials in → Authentication principal out.
- UserDetails: username, encoded password, authorities, account flags.
- UserDetailsService: load the account from your Orders user store by username/email.
- PasswordEncoder:
matchesraw vs stored hash — never compare strings yourself. - AuthenticationManager: orchestrates providers that validate credentials.
- SecurityContextHolder: thread-bound access to the current principal.
Step-by-step explanation
- Persist users with a BCrypt password hash column (never plaintext).
- Implement
UserDetailsService.loadUserByUsernameagainst that store. - Expose a
PasswordEncoderbean (BCryptPasswordEncoder). - On login success, either establish a session (rare for APIs) or issue tokens for later bearer auth.
Informative example
DB-backed UserDetailsService for Orders accounts.
@Servicepublic class DbUserDetailsService implements UserDetailsService {private final UserRepository users;public DbUserDetailsService(UserRepository users) {this.users = users;}@Overridepublic UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {return users.findByEmail(email).map(u -> User.withUsername(u.getEmail()).password(u.getPasswordHash()).authorities(u.getRoles().stream().map(r -> new SimpleGrantedAuthority("ROLE_" + r)).toList()).build()).orElseThrow(() -> new UsernameNotFoundException(email));}}@BeanPasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}
Real-world use
TechLearningPRO support staff and customers share one Orders API. Authentication loads the correct account and roles once; every downstream filter and @PreAuthorize expression reads the same principal. Without a single identity source, admin tools and mobile apps drift into inconsistent user ids.
Security implications
Broken authentication is OWASP territory.
- Always hash with a dedicated
PasswordEncoderbean. - Do not put secrets in example configs — use
${DB_PASSWORD}placeholders. - Invalidate sessions/tokens on password change.
Best practices
- Use email or opaque ids consistently as the username key.
- Keep authentication endpoints rate-limited and audited.
- Prefer a single
UserDetailsServiceimplementation over ad-hoc SQL in controllers.
Common mistakes
- Storing or logging raw passwords during login debugging.
- Throwing different errors for 'user not found' vs 'bad password' in a way that enables user enumeration without rate limits.
- Forgetting account locked/disabled flags on
UserDetails.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhat does Authentication represent?+
Answer
2IntermediateQuestionWhy use PasswordEncoder.matches instead of equals?+
Answer
3BeginnerQuestionWhere is the authenticated user stored for the request?+
Answer
SecurityContext, typically accessed via SecurityContextHolder.getContext().getAuthentication().Hands-on exercise
Lab. Seed one user with a BCrypt hash. Implement DbUserDetailsService. Authenticate via HTTP basic against a temporary secured Orders GET and print the principal name from a controller.
Summary
Orders authentication loads a principal into the SecurityContext. Next: authorization decides what that principal may do.