使用 Thymeleaf 的基本表单登录 SpringBoot 不起作用? - IT屋-程序员软件开发技术分享社区
首页
其他开发
使用 Thymeleaf 的基本表单登录 SpringBoot 不起作用?
使用 Thymeleaf 的基本表单登录 SpringBoot 不起作用?
[英] Basic form login SpringBoot with Thymeleaf doesn't work?
本文介绍了使用 Thymeleaf 的基本表单登录 SpringBoot 不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是春季靴的新手.我正在使用基本的 thymeleaf 表单登录.但是当我登录时它返回localhost:8080/login?error=true".我不知道为什么.我在数据库中的用户名和密码是正确的.也许我必须添加一个带有 post 方法的新控制器?请帮帮我
这里是我的安全配置类
protected void configure(HttpSecurity http) throws Exception {logger.info("-----configure(HttpSecurity http)");http.authorizeRequests().antMatchers("/**").permitAll().antMatchers("/user/**").hasAnyRole("USER").anyRequest().authenticated().和().formLogin().loginPage("/登录").defaultSuccessUrl("/home").permitAll().和().登出().permitAll().and().csrf().disable();}@自动连线public void configureGlobal(AuthenticationManagerBuilder auth) 抛出异常 {logger.info("-----configureGlobal(AuthenticationManagerBuilder auth)");auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);}
登录表单页面
<html lang="en" xmlns:th="http://www.thymeleaf.org"><头><title>登录</title><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>头部><身体><div class="容器"><h2>堆叠形式</h2><form th:action="@{/login}" method="post"><div class="form-group"><input type="text" name="username" id="username" class="form-control input-lg"placeholder="用户名" required="true" autofocus="true"/>
<div class="form-group"><input type="password" name="password" id="password" class="form-control input-lg"placeholder="密码" required="true"/>
<div class="form-group form-check"><label class="form-check-label"><input class="form-check-input" type="checkbox" name="remember">记住账号标签>
<a class="btn btn-success" th:href="@{'/register'}" role="button">注册</a><button type="submit" class="btn btn-primary">登录</button></表单>
</html>
我的控制器
@GetMapping("/login")公共字符串登录(){返回/登录";}
实体
@Entity(name = "dbo_user")公共类用户{@GeneratedValue(策略 = GenerationType.AUTO)@Column(name = "user_id")@ID私有整数 ID;私人字符串电子邮件;私人字符串密码;私人字符串用户名;}
解决方案
首先,User 类必须实现 UserDetails 接口,如下所示://用户详细信息方法
@Override公共收藏getAuthorities() {返回 this.roles.stream().map(SimpleGrantedAuthority::new).collect(toList());}@覆盖公共字符串 getUsername() {返回 this.getEmail();}@覆盖公共布尔 isAccountNonExpired() {返回真;}@覆盖公共布尔 isAccountNonLocked() {返回真;}@覆盖公共布尔 isCredentialsNonExpired() {返回真;}@覆盖公共布尔 isEnabled() {返回真;}@短暂的私人列表<字符串>角色 = Arrays.asList("ROLE_USER");公共列表<字符串>获取角色(){回归角色;}
第二,你需要一个像这样实现 UserDetailsService 的类:
@Service("customCustomerDetailsService")公共类 CustomUserDetailsService 实现 UserDetailsService {@自动连线私有 CredentialRepository 用户;@覆盖公共用户详细信息 loadUserByUsername(String email) {返回 this.users.findByEmail(email).orElseThrow(() -> new UsernameNotFoundException("Username: " + email + " not found"));}}
然后您将该类自动装配到您的安全配置类中
@AutowiredCustomUserDetailsService customCustomerDetailsService;
您需要在您的安全配置类中实现 DAO DaoAuthenticationProvider,如下所示:
@Beanpublic DaoAuthenticationProvider authenticationProvider() {DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();authProvider.setUserDetailsService(userDetailsService());authProvider.setPasswordEncoder(encoder());返回 authProvider;
我很确定这个问题会在这个平台上得到解答.
I am a newbie in spring boot. I'm using basic thymeleaf form login. But when I login it returns "localhost:8080/login?error=true". I don't know why. My username and password in the database are correct. Maybe I must add a new controller with post method? please help me
And here, this is my security config class
protected void configure(HttpSecurity http) throws Exception {
logger.info("-----configure(HttpSecurity http)");
http.authorizeRequests()
.antMatchers("/**").permitAll()
.antMatchers("/user/**").hasAnyRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.permitAll()
.and()
.logout()
.permitAll()
.and().csrf().disable();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
logger.info("-----configureGlobal(AuthenticationManagerBuilder auth)");
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
login form page
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Stacked form</h2>
<form th:action="@{/login}" method="post">
<div class="form-group">
<input type="text" name="username" id="username" class="form-control input-lg"
placeholder="UserName" required="true" autofocus="true"/>
</div>
<div class="form-group">
<input type="password" name="password" id="password" class="form-control input-lg"
placeholder="Password" required="true"/>
</div>
<div class="form-group form-check">
<label class="form-check-label">
<input class="form-check-input" type="checkbox" name="remember"> Remember me
</label>
</div>
<a class="btn btn-success" th:href="@{'/register'}" role="button">Register</a>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</body>
</html>
My controller
@GetMapping("/login")
public String login() {
return "/login";
}
The entity
@Entity(name = "dbo_user")
public class User {
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
@Id
private int id;
private String email;
private String password;
private String username;
}
解决方案
First of all, User class has to implement UserDetails interface like this:
// userdetails methods
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.roles.stream().map(SimpleGrantedAuthority::new).collect(toList());
}
@Override
public String getUsername() {
return this.getEmail();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Transient
private List<String> roles = Arrays.asList("ROLE_USER");
public List<String> getRoles() {
return roles;
}
2nd you need a class that implements UserDetailsService like this:
@Service("customCustomerDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private CredentialRepository users;
@Override
public UserDetails loadUserByUsername(String email) {
return this.users.findByEmail(email)
.orElseThrow(() -> new UsernameNotFoundException("Username: " + email + " not found"));
}
}
Then you autowire that class into your security config class
@Autowired
CustomUserDetailsService customCustomerDetailsService;
You need to implement DAO DaoAuthenticationProvider in your security config class like this:
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService());
authProvider.setPasswordEncoder(encoder());
return authProvider;
I'm quite sure this question would have been answered on this platform.
这篇关于使用 Thymeleaf 的基本表单登录 SpringBoot 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文