Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 39

    Authentication

    Authentication answers who are you?.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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: matches raw 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

    1. Persist users with a BCrypt password hash column (never plaintext).
    2. Implement UserDetailsService.loadUserByUsername against that store.
    3. Expose a PasswordEncoder bean (BCryptPasswordEncoder).
    4. 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.

    java
    @Service
    public class DbUserDetailsService implements UserDetailsService {
    private final UserRepository users;
    public DbUserDetailsService(UserRepository users) {
    this.users = users;
    }
    @Override
    public 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));
    }
    }
    @Bean
    PasswordEncoder 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 PasswordEncoder bean.
    • 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 UserDetailsService implementation 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.

    3 questions
    1BeginnerQuestionWhat does Authentication represent?+

    Answer

    A proven identity (principal) plus authorities and a flag indicating whether authentication succeeded.
    2IntermediateQuestionWhy use PasswordEncoder.matches instead of equals?+

    Answer

    Hashes include salt and algorithm metadata; the encoder understands the format and resists timing-naive compares.
    3BeginnerQuestionWhere is the authenticated user stored for the request?+

    Answer

    In the 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.

    Ready to mark this lesson complete?Track your journey across the entire course.