Servicelag
Du skal oprette en separat service
implementering af org.springframework.security.core.userdetails.UserDetailsService
og injicer det i AuthenticationManagerBuilder
.
@Component
public class SecUserDetailsService implements UserDetailsService{
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
/*Here add user data layer fetching from the MongoDB.
I have used userRepository*/
User user = userRepository.findByUsername(username);
if(user == null){
throw new UsernameNotFoundException(username);
}else{
UserDetails details = new SecUserDetails(user);
return details;
}
}
}
Model
UserDetails
Bør også implementeres. Dette er POJO'en, som vil holde brugerens autentificerede detaljer inden foråret. Du kan inkludere dit Entity-dataobjekt pakket inde i det, som jeg har gjort.
public class SecUserDetails implements UserDetails {
private User user;
public SecUserDetails(User user) {
this.user = user;
}
......
......
......
}
Sikkerhedskonfiguration
Autowire tjenesten, som vi oprettede før, og sæt den i AuthenticationManagerBuilder
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
SecUserDetailsService userDetailsService ;
@Autowired
public void configAuthBuilder(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(userDetailsService);
}
}