注册页面用户未保存在 DB Spring Boot 中
After registration page user isn't saved on DB Springboot
我只想使用 springboot
和 thymeleaf
在我的网站上注册一个用户,问题是当用户点击“提交”时,在填写注册表以保存其凭据后,这个操作还没有完成,我进入了 login
页面。
我确定注册没有完成,因为当我尝试登录时它不成功并且“凭据”和“用户”表都是空的。
这是注册表单,我正在保存“用户”和“凭据”两个不同的实体:
<form th:action="@{/process_register}" method="post">
<label for="username">Email:</label>
<input type="email" name="username" id="username" required th:field="${credentials.username}"/>
<label for="password">Password:</label>
<input type="password" name="password" id="password" required th:field="${credentials.password}"/>
<label for="name">Nome:</label>
<input type="name" name="name" id="name" th:field="${user.name}" required />
<button type="submit" class="btn btn-primary">Register</button>
<a th:href="@{/login}" href="login.html" > or login</a>
</form>
这是 /process_register
控制器:
@PostMapping("/process_register")
public String processRegister(@ModelAttribute("credentials")Credentials credentials,@ModelAttribute("user") User user) {
credentials.setUser(user);
credentialService.saveCredentials(credentials);
System.out.println("Ho invocato saveCredentials");
return "login";
}
saveCredentials()
方法:
@Transactional
public Credentials saveCredentials(Credentials credentials) {
credentials.setPassword(this.passwordEncoder.encode(credentials.getPassword()));
return this.credentialsRepository.save(credentials);
}
其中 credentialsRepository extends CrudRepository
.
编辑:
授权配置:
@Configuration
@EnableWebSecurity
public class AuthConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
DataSource datasource;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// authorization paragraph: qui definiamo chi può accedere a cosa
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/",
"/index",
"/login",
"/collection/*",
"/collections",
"/NFTS",
"/signup_form",
"/register",
"/css/**",
"zzz",
"/images/**").permitAll()
.antMatchers(HttpMethod.POST, "/login", "/register").permitAll()
.antMatchers(HttpMethod.GET, "/admin/**").hasAnyAuthority(ADMIN_ROLE)
.antMatchers(HttpMethod.POST, "/admin/**").hasAnyAuthority(ADMIN_ROLE)
.anyRequest().authenticated()
.and().formLogin()
.loginPage("/login")
.defaultSuccessUrl("/default")
.and().logout()
.logoutUrl("/logout")
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/index")
.invalidateHttpSession(true)
.clearAuthentication(true).permitAll();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
//use the autowired datasource to access the saved credentials
.dataSource(this.datasource)
//retrieve username and role
.authoritiesByUsernameQuery("SELECT username, role FROM credentials WHERE username=?")
//retrieve username, password and a boolean flag specifying whether the user is enabled or not (always enabled in our case)
.usersByUsernameQuery("SELECT username, password, 1 as enabled FROM credentials WHERE username=?");
/*auth.inMemoryAuthentication()
.withUser("user1").password(passwordEncoder().encode("user1")).roles("USER")
.and()
.withUser("user2").password(passwordEncoder().encode("user2")).roles("USER")
.and()
.withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN_ROLE");*/
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
查看 github 存储库后:您需要针对 AuthConfiguration
中配置的身份验证过滤器创建控制器。只有少数路径允许未经授权的用户访问 i.a。 /register
和 /login
.
由于 /process_register
未列入白名单,因此 POST 请求不会到达控制器。它被过滤器捕获并重定向到登录页面。
要解决此问题,您可以执行以下操作:
- 在您的控制器中将
@PostMapping("/process_register")
更改为 @PostMapping("/register")
。
- 在模板中将
th:action="@{/process_register}"
更改为 th:action="@{/register}"
。
完成后,注册表应该可以使用了。
顺便说一句:
你不应该这样使用 th:field
。它应该与表单支持 bean (th:object
) 一起使用 - 请参考 the documentation.
我只想使用 springboot
和 thymeleaf
在我的网站上注册一个用户,问题是当用户点击“提交”时,在填写注册表以保存其凭据后,这个操作还没有完成,我进入了 login
页面。
我确定注册没有完成,因为当我尝试登录时它不成功并且“凭据”和“用户”表都是空的。
这是注册表单,我正在保存“用户”和“凭据”两个不同的实体:
<form th:action="@{/process_register}" method="post">
<label for="username">Email:</label>
<input type="email" name="username" id="username" required th:field="${credentials.username}"/>
<label for="password">Password:</label>
<input type="password" name="password" id="password" required th:field="${credentials.password}"/>
<label for="name">Nome:</label>
<input type="name" name="name" id="name" th:field="${user.name}" required />
<button type="submit" class="btn btn-primary">Register</button>
<a th:href="@{/login}" href="login.html" > or login</a>
</form>
这是 /process_register
控制器:
@PostMapping("/process_register")
public String processRegister(@ModelAttribute("credentials")Credentials credentials,@ModelAttribute("user") User user) {
credentials.setUser(user);
credentialService.saveCredentials(credentials);
System.out.println("Ho invocato saveCredentials");
return "login";
}
saveCredentials()
方法:
@Transactional
public Credentials saveCredentials(Credentials credentials) {
credentials.setPassword(this.passwordEncoder.encode(credentials.getPassword()));
return this.credentialsRepository.save(credentials);
}
其中 credentialsRepository extends CrudRepository
.
编辑: 授权配置:
@Configuration
@EnableWebSecurity
public class AuthConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
DataSource datasource;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// authorization paragraph: qui definiamo chi può accedere a cosa
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/",
"/index",
"/login",
"/collection/*",
"/collections",
"/NFTS",
"/signup_form",
"/register",
"/css/**",
"zzz",
"/images/**").permitAll()
.antMatchers(HttpMethod.POST, "/login", "/register").permitAll()
.antMatchers(HttpMethod.GET, "/admin/**").hasAnyAuthority(ADMIN_ROLE)
.antMatchers(HttpMethod.POST, "/admin/**").hasAnyAuthority(ADMIN_ROLE)
.anyRequest().authenticated()
.and().formLogin()
.loginPage("/login")
.defaultSuccessUrl("/default")
.and().logout()
.logoutUrl("/logout")
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/index")
.invalidateHttpSession(true)
.clearAuthentication(true).permitAll();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
//use the autowired datasource to access the saved credentials
.dataSource(this.datasource)
//retrieve username and role
.authoritiesByUsernameQuery("SELECT username, role FROM credentials WHERE username=?")
//retrieve username, password and a boolean flag specifying whether the user is enabled or not (always enabled in our case)
.usersByUsernameQuery("SELECT username, password, 1 as enabled FROM credentials WHERE username=?");
/*auth.inMemoryAuthentication()
.withUser("user1").password(passwordEncoder().encode("user1")).roles("USER")
.and()
.withUser("user2").password(passwordEncoder().encode("user2")).roles("USER")
.and()
.withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN_ROLE");*/
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
查看 github 存储库后:您需要针对 AuthConfiguration
中配置的身份验证过滤器创建控制器。只有少数路径允许未经授权的用户访问 i.a。 /register
和 /login
.
由于 /process_register
未列入白名单,因此 POST 请求不会到达控制器。它被过滤器捕获并重定向到登录页面。
要解决此问题,您可以执行以下操作:
- 在您的控制器中将
@PostMapping("/process_register")
更改为@PostMapping("/register")
。 - 在模板中将
th:action="@{/process_register}"
更改为th:action="@{/register}"
。
完成后,注册表应该可以使用了。
顺便说一句:
你不应该这样使用 th:field
。它应该与表单支持 bean (th:object
) 一起使用 - 请参考 the documentation.