Ich verwende Spring Security 5 und Spring MVC -Projekt, die durch eine benutzerdefinierte DAO -Authentifizierung durch eine Klasse, die UserDetailsService , personService -, verwendet. Die Entitäten sind Person , Student und einige andere, die hier nicht relevant sind. Diese Entitäten werden mithilfe von SQL -Skripten initialisiert und protokollieren mit der Spring Security mithilfe dieser Skript -Initialisierungsentitäten einwandfrei. Wenn ich sie in der Datenbank speichere und dann zurück gehe und versuche, diese neu erstellte Student (und Person durch Erbschaft) zu melden, verweigert Frühlingssicherheit die Authentifizierung. Unter Verwendung des Debuggers stellte ich fest, dass es intern ein Javax.Persistence.NoresultFoundException mit einer Nachricht, die keine Entität für Abfrage gefunden hat, geworfen hat. Aber ich habe an mehreren Stellen bestätigt, dass die neue Entität in der Datenbank tatsächlich existiert. Unten finden Sie meine Frühlingssicherheitskonfigurationsklasse und einige Screenshots von mir, die das Problem reproduzieren, und einige Ergebnisse beim Ausführen des Debuggers. < /P>
Code: Select all
SecurityConfig.java
Code: Select all
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private PersonService personService;
private CustomAuthentication customAuthentication;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**",
"/static/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/*").hasAnyRole("STUDENT", "FACULTY_MEMBER", "STAFF_MEMBER")
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/userAuth")
.successHandler(customAuthentication)
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.permitAll();
}
@Bean
public CsrfTokenRepository repo() {
HttpSessionCsrfTokenRepository repo = new HttpSessionCsrfTokenRepository();
repo.setParameterName("_csrf");
repo.setHeaderName("X-CSRF-TOKEN");
return repo;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
auth.setUserDetailsService(personService);
auth.setPasswordEncoder(passwordEncoder());
return auth;
}
@Autowired
public void setPersonService(PersonService personService) {
this.personService = personService;
}
@Autowired
public void setCustomAuthentication(CustomAuthentication customAuthentication) {
this.customAuthentication = customAuthentication;
}
Code: Select all
PersonRepo
Code: Select all
@Service
public class PersonServiceImpl implements PersonService {
private PasswordEncoder passwordEncoder;
private PersonRepo personRepo;
@Override
public Person findByUsername(String username) {
return personRepo.findByUsername(username);
}
@Override
public void save(Person person) {
personRepo.save(person);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Logger logger = Logger.getLogger(getClass().toString());
logger.info("Inside the loadUserByUsername method");
Person person = this.findByUsername(username);
if (person == null) {
logger.info("Person with username: " + username + " was not found!");
throw new UsernameNotFoundException("Could not find Person with username " + username);
}
logger.info("User was successfully retrieved from database");
Collection grantedAuthorityRoles = person.getRoles().stream().map(
role -> new SimpleGrantedAuthority(role.getRole().name())).collect(Collectors.toList());
return new User(person.getUsername(), person.getPassword(), grantedAuthorityRoles);
}
@Autowired
public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
@Autowired
public void setPersonRepo(PersonRepo personRepo) {
this.personRepo = personRepo;
}
}
Code: Select all
@PostMapping("/save_student")
public String saveStudent(@ModelAttribute("student") Student student) {
student.setUsername(student.getFirstName().charAt(0) + student.getLastName().toLowerCase());
student.setPassword(passwordEncoder.encode(student.getPassword()));
student.setRoles(List.of(roleRepo.getRoleByName(RoleEnum.ROLE_STUDENT.name())));
student.setVersion(1);
studentRepo.save(student);
if (personService.loadUserByUsername(student.getUsername()) == null) {
throw new EntityNotFoundException();
} else {
logger.info("Person with username " + student.getUsername() + " was indeed found.");
}
return "redirect:list_students";
}
@GetMapping("/list_students")
public String listStudents(Model model) {
model.addAttribute("students", studentRepo.findAll());
model.addAttribute("people", personRepo.findAll());
return "all_students";
}
< /code>
Diese Screenshots versuchen, den Fehler zu demonstrieren. Nachdem ich auf die Taste Register geklickt habe, wird das @PostMapping ("/save_student")
https://github.com/dcechano/universityM ... ktrace.txt