У меня есть простое приложение Spring Boot 2.xx с Spring Data JPA MySQL, я должен защитить это веб-приложение с помощью Spring Security (особенно конфигурации Java), поэтому я нашел много ресурсов в Интернете, чтобы выполнить работу, но напрасно , некоторые примеры были слишком сложны для понимания, а другие никогда не помогали мне.Я придумал эту secure-spring-demo , которая тоже не работает.некоторые фрагменты кода
класс WebSecurityConfig равен
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsServiceImpl userDetailsService;
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public DaoAuthenticationProvider authProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http
.authorizeRequests()
.antMatchers("/login*", "/register", "/").anonymous()
.antMatchers("/secure/*").hasAnyAuthority("ADMIN").anyRequest().authenticated()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.and()
.logout().logoutSuccessUrl("/login");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
, а класс UserDetailsServiceImpl равен
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
private final UserService userService;
@Autowired
public UserDetailsServiceImpl(UserService userService) {
this.userService = userService;
}
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
User user = userService.findByUserEmail(s);
if (user == null){
throw new UsernameNotFoundException("User with " + s + " not found!");
}
return new org.springframework.security.core.userdetails.User(
user.getUserEmail(), user.getUserPassword(), user.getRoles());
}
}
, контроллер -
@Controller
public class UserController {
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private SecurityService securityService;
//Omitting other mappings
@GetMapping(value = "/login")
public String getLogin(Model model,
@RequestParam(value = "error", required = false) String error){
if (null != error && error.equalsIgnoreCase("true")){
model.addAttribute("loginError", "Unable to Login");
}
return "login";
}
@PostMapping(value = "/login")
public String postLogin(@RequestParam(value = "userEmail") String userEmail,
@RequestParam(value = "userPassword") String userPassword){
logger.debug(userEmail + " and " + userPassword );
boolean loginResult = securityService.login(userEmail, userPassword);
return (loginResult ? "redirect:/secure/home" : "redirect:/login?error=true");
}
}
со всем этимпользователь не может войти с правильными учетными данными.