当前位置: 首页 > 知识库问答 >
问题:

用百里香叶的基本形态登录SpringBoot不起作用?

白萧迟
2023-03-14

我是一个春靴新手。我使用基本的百里香形式登录。但是当我登录时,它返回“localhost:8080/login?错误=真”。我不知道为什么。我在数据库中的用户名和密码是正确的。也许我必须用post方法添加一个新的控制器?请帮助我

这是我的安全配置课程

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);
}

登录表单页面

<!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>

我的控制器

    @GetMapping("/login")
    public String login() {
        return "/login";
    }

实体

@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;
}

共有2个答案

哈涵容
2023-03-14

您是否使用百里香叶安全附加功能?如果是这样,那么您需要在登录页面上的 maven/gradle 和 thymeleaf 命名空间中包含依赖项。

   <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        <version>3.0.4.RELEASE</version>
   </dependency>

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:th="http://www.thymeleaf.org"
  xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
  xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5" lang="en">
太叔睿
2023-03-14

首先,用户类必须像这样实现UserDetails接口:// userdetails方法

@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;
    }

第二,你需要一个实现UserDetailsService的类,如下所示:

@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"));


    }

}

然后将该类自动连接到安全配置类中

@Autowired
    CustomUserDetailsService customCustomerDetailsService;

您需要在安全配置类中实现DAO DaoAuthenticationProvider,如下所示:

@Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService());
        authProvider.setPasswordEncoder(encoder());

        return authProvider;

我很确定这个问题会在这个平台上得到回答。

 类似资料:
  • 我不明白,如果html模板与我在ModelAndView中获得的属性链接,如何将RESTFull服务的@Controller更改为@RestController 在胸腺叶模板中 但我想进入索引页面,在后台获取用户名 我可以使用ajax来更新标记“p”,但这样使用thymeleaf并没有什么好处,我可以使用jsp。那么,在Rest时使用thymeleaf的最佳方式是什么?它是否合理?

  • 我用百里香模板发送电子邮件。我有一个模板,比如: 如果为空或,我不想发送电子邮件。我可以设置任何Thymeleaf属性来生成错误并且不会发送邮件吗?因为在没有值的电子邮件中发送“My name is”没有任何意义。 我从Thymeleaf上下文中获取所有值,变量可能是不同类型的,例如、等。我也尝试了以下方法,但它并没有解决我的问题,因为对象总是可用的:

  • 我是Springboot的初学者,所以决定在购物车上工作。似乎找不到org.springframework.expression.spel.SpelEvalue ationException: EL1007E的根:在null上找不到属性或字段'name'。嵌套异常是org.thymeleaf.exceptions.TemplateProcessingException: Exception评估Sp

  • 我正在尝试在我的应用程序中开发一个新的密码功能。当用户打开设置新密码页面时,它有3个输入字段:新密码,再次输入新密码,以及一个隐藏字段uuId。有了这个uuid可以帮助我正确更新数据库记录。我已经使用了双控制器方法,但有些地方出了问题,因为uuid字段没有填充。

  • 根据thymeleaf安全页面,我可以获取记录的用户名和角色,如下所示: 我有一个Web应用程序,其中身份验证是使用目录完成的,如下所示: 然后,在用户登录后,我有一个标题页面,我在我的所有页面中使用上面的thymeleaf标签来显示用户名,但我想看看是否有办法显示全名。 这里建议的解决方案对我不起作用: 我正在使用: 和使用:<代码> 在类型org . spring framework . se

  • 您好,我是spring新手,我正试图用thymeleaf显示一个简单的html文件,但在呈现视图时遇到了问题。它只显示字符串“index”,而不显示index中的html内容。html。有人能告诉我我做错了什么吗 调度员servle。xml文件: TestController.java: 指数html文件:在webapp/templates/index中定义。html