Users from the database
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
UserDetailsServicehas one method:loadUserByUsername. It returns aUserDetails(name, password hash, authorities).- Load the user with a repository; throw
UsernameNotFoundExceptionif missing. - Spring Security compares the submitted password with the stored hash using a
PasswordEncoder. - Map your role column to authorities;
hasRole("ADMIN")looks forROLE_ADMIN. - Never store plain passwords (next module covers hashing).
Draft outline details
Demonstration
@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.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.