- Spring Security(Third Edition)
- Mick Knutson Robert Winch Peter Mularien
- 221字
- 2025-04-04 17:54:29
The UserDetailsService object
Let's take a look at the following steps to add the UserDetailsService object:
- Now, we need to add a new implementation of the UserDetailsService object, we will use our CalendarUserRepository interface to authenticate and authorize users again, with the same underlying RDBMS, but using our new JPA implementation as follows:
//com/packtpub/springsecurity/service/UserDetailsServiceImpl.java
package com.packtpub.springsecurity.service;
... omitted for brevity ...
@Service
public class UserDetailsServiceImpl
implements UserDetailsService {
@Autowired
private CalendarUserRepository userRepository;
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(final String username)
throws UsernameNotFoundException {
CalendarUser user = userRepository.findByEmail(username);
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
for (Role role : user.getRoles()){
grantedAuthorities.add(new SimpleGrantedAuthority
(role.getName()));
}
return new org.springframework.security.core.userdetails.User(
user.getEmail(), user.getPassword(), grantedAuthorities);
}
}
- Now, we have to configure Spring Security to use our custom UserDetailsService object, as follows:
//com/packtpub/springsecurity/configuration/SecurityConfig.java
package com.packtpub.springsecurity.configuration;
... omitted for brevity ...
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {\
@Autowired
private UserDetailsService userDetailsService;
@Override
public void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
@Bean
@Override
public UserDetailsService userDetailsService() {
return new UserDetailsServiceImpl();
}
...
}
- Start the application and try logging in to the application. Any of the configured users can now log in and create new events. You can also create a new user and will be able to log in as the new user immediately.
Your code should now look like calendar05.04-calendar.