In your application, you need to securely store user passwords. What approach would you take to implement password encoding in Spring Security? Discuss the choice of encoding algorithm and how to verify passwords during authentication.

Secure password storage in Spring Security relies on the PasswordEncoder abstraction, with BCrypt as the recommended algorithm because it's a slow, salted, one-way hash specifically designed to resist brute-force and rainbow-table attacks.

Key Points

Example

On registration, the raw password is hashed with BCryptPasswordEncoder before saving to the database; at login, the raw password entered is never compared directly—matches() re-hashes it with the stored salt and compares digests.

PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

// Registration
String encodedPassword = passwordEncoder.encode(rawPassword);
userRepository.save(new User(username, encodedPassword));

// Login verification
boolean isMatch = passwordEncoder.matches(rawPassword, storedEncodedPassword);

Interview Tip

A concise interview answer is

I'd use Spring Security's PasswordEncoder interface with BCryptPasswordEncoder, which salts and hashes passwords automatically with a tunable work factor. Passwords are hashed with encode() at registration and never stored raw, and matches() re-hashes the login attempt to compare against the stored hash during authentication.

Last updated: 16 July 2026

Previous question: You have a service layer in your application that contains methods that should only be accessed by certain roles. How would you implement method-level security using Spring Security annotations to restrict access to these methods based on user roles?

More Spring Security - Level II interview questions

All Spring Security - Level II questions