AI Hints
Home›Spring Boot Tutorial›Users and Passwords, Password Encoding and Roles
Spring Boot · Lesson 95 of 120

Password Encoding

Never store plain text.

⏱ 2 min read▶ Video at 2:06:01🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

If passwords are stored as plain text, anyone who sees the database sees every password. Instead, we store a hash, a scrambled version that can't be reversed.

  • Plain text is dangerous
  • Store a hash
  • Can't be reversed

How hashing works

BCrypt turns a password into a long hash. It adds random salt, so the same password gives a different hash each time. To log in, BCrypt checks a typed password against the stored hash. And it's slow on purpose, so guessing millions of passwords takes far too long.

keyvalue
BCryptthe standard choice
Saltrandom, per password
Checkmatches(typed, hash)
Slowon purpose

BCrypt for real

A Password Encoder bean provides BCrypt. The runner encodes the same password twice. Then it checks the right password, and a wrong one. Run it. The two hashes are different, because of the salt. But the right password matches. And the wrong one doesn't.

HashDemo.javajava
@Component
public class HashDemo implements CommandLineRunner {

    private final PasswordEncoder encoder;

    public HashDemo(PasswordEncoder encoder) { this.encoder = encoder; }

    @Override
    public void run(String... args) {
        String hash1 = encoder.encode("reader1");
        String hash2 = encoder.encode("reader1");
        System.out.println(hash1);
        System.out.println(hash2);
        System.out.println("Same text? " + hash1.equals(hash2));
        System.out.println("reader1 matches? " + encoder.matches("reader1", hash1));
        System.out.println("wrong matches? " + encoder.matches("wrong", hash1));
    }
}
Output
$2a$10$M5pA25ix2mfVbtRMBxVU2OOgyQaJZLkK2xCYAzcG37UAYEoXnD94i
$2a$10$1DvYhM3dMpP4tWT3KlSKcuSMYQnxBNrkaa8HbmRPdG1VNdUNXXDwO
Same text? false
reader1 matches? true
wrong matches? false
Also uses SecurityConfig.java
@Configuration
public class SecurityConfig {
    @Bean
    PasswordEncoder encoder() { return new BCryptPasswordEncoder(); }
}
Also uses _profile
security

Users with hashed passwords

Now the users service asks for the encoder, and stores a hash, not the password. Logging in works exactly as before. Run it. Sam logs in with reader one. Spring compared it with the hash, automatically.

SecurityConfig.javajava
@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
            .httpBasic(Customizer.withDefaults()).csrf(csrf -> csrf.disable());
        return http.build();
    }

    @Bean
    PasswordEncoder encoder() { return new BCryptPasswordEncoder(); }
    @Bean
    UserDetailsService users(PasswordEncoder encoder) {
        return new InMemoryUserDetailsManager(
            User.withUsername("sam").password(encoder.encode("reader1"))
                .roles("USER").build());
    }
}
Output
You are sam, roles: [ROLE_USER]
Also uses BookController.java
@RestController
public class BookController {

    @GetMapping("/books")
    public List<String> books() { return List.of("Dune", "Circe"); }

    @DeleteMapping("/books/{id}")
    public String delete(@PathVariable int id) { return "Deleted book " + id; }

    @GetMapping("/me")
    public String me(Authentication auth) {
        return "You are " + auth.getName() + ", roles: " + auth.getAuthorities().stream()
            .map(GrantedAuthority::getAuthority).filter(a -> a.startsWith("ROLE_")).toList();
    }
}
Also uses _curl.sh
curl -u sam:reader1 localhost:8080/me
Also uses _profile
security

Summary

Never store plain passwords. A BCrypt Password Encoder stores salted hashes, and checks logins against them. Next, roles.

Key takeaways
  • BCryptPasswordEncoder
  • Salted hashes
  • matches()
Next up: Roles — what users may do