Подключил к учебному проекту Spring security. Но не слишком успешно. Пользовался этим tutorial:
https://tutorials.webencyclop.com/spring-boot/03-create-user-login-registration/#define-controllers-for-login-registration Подскажите пожалуйста почему Spring выбрасывает SQL Exception java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0). когда я пытаюсь залогониться. Провел куча часов пытаясь выяснить что не так, но так и не выяснил. Мой проект на гитхаб: https://github.com/SerhiiRyzhkov/english
Мой конфиг:
@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
private DataSource dataSource;
@Value("${spring.queries.users-query}")
private String usersQuery;
@Value("${spring.queries.roles-query}")
private String rolesQuery;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().usersByUsernameQuery(usersQuery).authoritiesByUsernameQuery(rolesQuery)
.dataSource(dataSource).passwordEncoder(bCryptPasswordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
// URLs matching for access rights
.antMatchers("/").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/register").permitAll()
.antMatchers("/home/**").hasAnyAuthority("SUPER_USER", "ADMIN_USER", "SITE_USER")
.anyRequest().authenticated()
.and()
// form login
.csrf().disable().formLogin()
.loginPage("/login")
.failureUrl("/?error=true")
.defaultSuccessUrl("/home")
.usernameParameter("email")
.passwordParameter("password")
.and()
// logout
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").and()
.exceptionHandling()
.accessDeniedPage("/access-denied");
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");
}
}
Мой контроллер:
@Controller
public class AuthenticationController {
@RequestMapping(value = { "/login" }, method = RequestMethod.GET)
public ModelAndView login() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("login");
return modelAndView;
}
@RequestMapping(value = "/register", method = RequestMethod.GET)
public ModelAndView register() {
ModelAndView modelAndView = new ModelAndView();
// User user = new User();
// modelAndView.addObject("user", user);
modelAndView.setViewName("register");
return modelAndView;
}
@RequestMapping(value = "/home")
public ModelAndView home() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("home");
return modelAndView;
}
}
JSP форма:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>English - login</title>
</head>
<body>
<form th:action="@{/login}" method="POST">
Login
<br>
<input type="text" id="email" name="email" th:placeholder="Email"/>
<br>
Password
<br>
<input type="password" id="password" name="password" th:placeholder="Password"/>
<br>
<br>
<button name="Submit" value="Login" type="Submit" th:text="Login"></button>
<a href="/recover-password">Forgot password?</a>
</form>
</body>
</html>
Мой properies file:
#Spring Security login queries
security.basic.enabled=false
spring.queries.users-query=select email, password, '1' as enabled from auth_user where email=? and status='VERIFIED'
spring.queries.roles-query=select u.email, r.role_name from auth_user u inner join auth_user_role ur on(u.auth_user_id=ur.auth_user_id) inner join auth_role r on(ur.auth_role_id=r.auth_role_id) where u.email=?
Когда я пытаюсь залогониться, я вижу что данные с формы уходят в контроллер:
Я так понимаю, что проблема в моем sql statement, но он практически такой же по синтаксису как дефолтный запрос в JdbcDaoImpl.class
.
update
SQL Exception java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
Возникает в момент когда в форме логин пароль я нажимаю кнопку сабмит. В этот момент происходит запрос в базу данных, проверить имеются ли такие email и пароль в БД, и каков статус данного юзера? (забанен или нет). Сами запросы вынесены в файл application.properies - запросы приведены выше. Эти запросы инницируются с помощью
auth.jdbcAuthentication().usersByUsernameQuery(usersQuery).authoritiesByUsernameQuery(rolesQuery)
.dataSource(dataSource).passwordEncoder(bCryptPasswordEncoder);
в классе SecurityConfiga. А сами statements передаются переменными usersQuery и rolesQuery. Ожидалось, что при вводе логина и пароля, SecurityConfig проверяет есть ли в базе такой пользователь или нет и впускает в приложение если пароль совпал в БД и статус usera VERIFIED. но меня не отправляет на страницу home и нет сообщения о успешном логине, а выбрасывается исключение
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0)
?