Users, Roles and Password Encoding

Harry · 14 Sep 2026 · 1 views
Advertisement
Advertisement

Never store plain passwords

Passwords must be stored hashed, never in plain text. Spring Security’s BCryptPasswordEncoder applies a slow, salted hash designed to resist brute force. Expose it as a bean and Spring uses it to encode and to verify at login:

@Bean
PasswordEncoder passwordEncoder() {
  return new BCryptPasswordEncoder();
}

In-memory users (for demos)

@Bean
UserDetailsService users(PasswordEncoder encoder) {
  UserDetails admin = User.withUsername("admin")
      .password(encoder.encode("admin123"))
      .roles("ADMIN")
      .build();
  return new InMemoryUserDetailsManager(admin);
}

Loading users from a database

In real apps you implement UserDetailsService to fetch the user from your own table and return their hashed password and roles:

@Service
public class DbUserDetailsService implements UserDetailsService {
  private final UserRepository repo;
  public DbUserDetailsService(UserRepository repo) { this.repo = repo; }

  @Override
  public UserDetails loadUserByUsername(String username) {
    AppUser u = repo.findByUsername(username)
        .orElseThrow(() -> new UsernameNotFoundException(username));
    return User.withUsername(u.getUsername())
        .password(u.getPasswordHash())   // already BCrypt-hashed
        .roles(u.getRole())
        .build();
  }
}

Spring calls this at login, then compares the submitted password against the stored hash using your PasswordEncoder.

Roles vs authorities

A role is just an authority with a ROLE_ prefix. .roles("ADMIN") is shorthand for the authority ROLE_ADMIN. Keep this in mind – it explains the prefix you will see in authorization rules.

Key points

  • Store passwords with BCryptPasswordEncoder; expose it as a bean.
  • InMemoryUserDetailsManager is fine for demos; implement UserDetailsService for real users.
  • Spring loads the user by name and verifies the password against the stored hash.
  • A role is an authority with a ROLE_ prefix (roles("ADMIN")ROLE_ADMIN).
Share this post:

Comments (0)

Please login or register to comment.