Skip to content
Ameen Abozaid
Planned lessonJNR-036-L03

Users from the database

  • Lesson 3 of 8
  • Junior
On This Lesson 4 topics

This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.

In this lesson

authenticate against users stored in the Shop database.

Planned topics

  • UserDetailsService has one method: loadUserByUsername. It returns a UserDetails (name, password hash, authorities).
  • Load the user with a repository; throw UsernameNotFoundException if missing.
  • Spring Security compares the submitted password with the stored hash using a PasswordEncoder.
  • Map your role column to authorities; hasRole("ADMIN") looks for ROLE_ADMIN.
  • Never store plain passwords (next module covers hashing).
Draft outline details

Demonstration

java
@Service
class DbUserDetailsService implements UserDetailsService {
    public UserDetails loadUserByUsername(String email) {
        var u = users.findByEmail(email).orElseThrow(() -> new UsernameNotFoundException("no user"));
        return User.withUsername(u.getEmail()).password(u.getPasswordHash())
                   .roles(u.getRole()).build();
    }
}

Check your understanding

What does hasRole("ADMIN") look for?

Show answer

The authority ROLE_ADMIN.

Practice

Apply this lesson with the module's lab, exercises and quiz.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.