我的Spring-Boot自定义登录表单无法使用[更新]

如何解决我的Spring-Boot自定义登录表单无法使用[更新]

我是Spring-Boot的新手,目前,我正在开发具有MySQL数据库连接的自定义登录表单。

所以我已经开发了注册功能,并且可以正常工作。

但是当我尝试登录一个帐户时,它总是显示“无效的用户名和密码”。

我正在使用Eclipse IDE。

下面是Controller类:WebMvcConfiguration.java

@ComponentScan("org.springframework.security.samples.mvc")
@Controller
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer  {

    

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }

     @GetMapping("/login")
    public String login() {
      return "login";
    }
    
    @PostMapping("/customerAccount")
    public String authenticate() {
      // authentication logic here
      return "customerAccount";
    }
    
    @GetMapping("/adminDashboard")
    public String adminDashboard() {
        return "adminDashboard";
    }
    
    @GetMapping("/Category")
   public String Category() {
     return "Category";
   }
    @GetMapping("/Index")
   public String Index() {
     return "Index";
   }
    
    @PostMapping("/RatingAccount")
    public String RatingAccount() {
      return "RatingAccount";
    }
    
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/static/**").addResourceLocations("/resources/static/");
    } 
    
}


下面是UserAccountController.java

@RestController
@Controller
public class UserAccountController {

    @Autowired
    private CustomerRepository userRepository;

    @Autowired
    private ConfirmationTokenRepository confirmationTokenRepository;

    @Autowired
    private EmailSenderService emailSenderService;

    @RequestMapping(value="/register",method = RequestMethod.GET)
    public ModelAndView displayRegistration(ModelAndView modelAndView,Customer user)
    {
        modelAndView.addObject("user",user);
        modelAndView.setViewName("register");
        return modelAndView;
    }

    @RequestMapping(value="/register",method = RequestMethod.POST)
    public ModelAndView registerUser(ModelAndView modelAndView,Customer user)
    {

        Customer existingUser = userRepository.findByEmailIdIgnoreCase(user.getEmailId());
        if(existingUser != null)
        {
            modelAndView.addObject("message","This email already exists!");
            modelAndView.setViewName("error"); 
        }
        else
        {
            userRepository.save(user);

            ConfirmationToken confirmationToken = new ConfirmationToken(user);

            confirmationTokenRepository.save(confirmationToken);

            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setTo(user.getEmailId());
            mailMessage.setSubject("Complete Registration!");
            mailMessage.setFrom("rukshan033@gmail.com");
            mailMessage.setText("To confirm your account,please click here : "
            +"http://localhost:8082/confirm-account?token="+confirmationToken.getConfirmationToken());

            emailSenderService.sendEmail(mailMessage);

            modelAndView.addObject("emailId",user.getEmailId());

            modelAndView.setViewName("successfulRegisteration");
        }

        return modelAndView;
    }

    @RequestMapping(value="/confirm-account",method= {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView confirmUserAccount(ModelAndView modelAndView,@RequestParam("token")String confirmationToken)
    {
        ConfirmationToken token = confirmationTokenRepository.findByConfirmationToken(confirmationToken);

        if(token != null)
        {
            Customer user = token.getCustomer();
            //Customer user = userRepository.findByEmailIdIgnoreCase(token.getCustomer().getEmailId());
            user.setEnabled(true);
            userRepository.save(user);
            modelAndView.setViewName("accountVerified");
        }
        else
        {
            modelAndView.addObject("message","The link is invalid or broken!");
            modelAndView.setViewName("error");
        }

        return modelAndView;
    }
    
    @RequestMapping(value="/login",RequestMethod.POST})
   // @ResponseBody
    public ModelAndView login(ModelAndView modelAndView,@RequestParam("emailID")String email,@RequestParam("password")String password)
    {
        Customer user = userRepository.findByEmailIdIgnoreCase(email);
        
        if(user == null) {
            modelAndView.addObject("message1","Invalid E-mail. Please try again.");
            modelAndView.setViewName("login");
        }
        else if (user != null && user.getPassword()!=password) {
            modelAndView.addObject("message1","Incorrect password. Please try again.");
            modelAndView.setViewName("login");
        }
        else if (user != null && user.getPassword()==password && user.isEnabled()==false) {
            modelAndView.addObject("message1","E-mail is not verified. Check your inbox for the e=mail with a verification link.");
            modelAndView.setViewName("login");
        }
        else if (user != null && user.getPassword()==password && user.isEnabled()==true) { 
            modelAndView.addObject("message1","Welcome! You are logged in.");
            modelAndView.setViewName("customerAccount");
        }
        return modelAndView;
    }
    

    @RequestMapping(value="/customerDetails",method = RequestMethod.GET)
    public ModelAndView displayCustomerList(ModelAndView modelAndView)
    {
        modelAndView.addObject("customerList",userRepository.findAll());
        modelAndView.setViewName("customerDetails");
        return modelAndView;
    }
    
    
    
    // getters and setters
    public CustomerRepository getUserRepository() {
        return userRepository;
    }

    public void setUserRepository(CustomerRepository userRepository) {
        this.userRepository = userRepository;
    }

    public ConfirmationTokenRepository getConfirmationTokenRepository() {
        return confirmationTokenRepository;
    }

    public void setConfirmationTokenRepository(ConfirmationTokenRepository confirmationTokenRepository) {
        this.confirmationTokenRepository = confirmationTokenRepository;
    }

    public EmailSenderService getEmailSenderService() {
        return emailSenderService;
    }

    public void setEmailSenderService(EmailSenderService emailSenderService) {
        this.emailSenderService = emailSenderService;
    }
    
    
}




下面是“安全配置”类:SecurityConfig.java

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity http) throws Exception {
     
        http
        .authorizeRequests()
        .antMatchers(
            "/Index/**","/Category/**","/register**","/css/**","/fonts/**","/icon-fonts/**","/images/**","/img/**","/js/**","/Source/**").permitAll()
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/login")
        .permitAll()        
        .and()
        .logout()
        .permitAll();
    
    }
    
}

下面是Thymeleaf登录页面:login.html

<html xmlns:th="http://www.thymeleaf.org" xmlns:tiles="http://www.thymeleaf.org">
  <head>
    <title tiles:fragment="title">Login</title>
  </head>
  <body>
    <div tiles:fragment="content">
        <form name="f" th:action="@{/login}" method="post">               
            <fieldset>
                <legend>Please Login</legend>
                <div th:if="${param.error}" class="alert alert-error">    
                    Invalid username and password.
                </div>
                <div th:if="${param.logout}" class="alert alert-success"> 
                    You have been logged out.
                </div>
                <label for="emailId">E-mail</label>
                <input type="text" id="emailId" name="emailId"/>        
                <label for="password">Password</label>
                <input type="password" id="password" name="password"/>    
                <div class="form-actions">
                    <button type="submit" class="btn">Log in</button>
                </div>
            </fieldset>
        </form>
    </div>
  </body>
</html>

下面是我应重定向至的页面:customerAccount.html

<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
  xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Welcome</title>
    </head>
    <body>
    <form th:action="@{/customerAccount}" method="post">
        <center>
            <h3 th:inline="text">Welcome [[${#httpServletRequest.remoteUser}]]</h3>
        </center>
        
        <form th:action="@{/logout}" method="post">
            <input type="submit" value="Logout" />
        </form>
    </form>
    </body>
</html> 

编辑

新的UserDetailsS​​ervice类:

public class CustomerDetailsService implements UserDetailsService{
    
    @Autowired
    private CustomerRepository customerRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Customer customer = customerRepository.findByEmailIdIgnoreCase(username);
        if (customer == null) {

            throw new UsernameNotFoundException(username);
        }

        return new MyUserPrincipal(customer);
    }

}

class MyUserPrincipal implements UserDetails {
    private Customer customer;
 
    public MyUserPrincipal(Customer customer) {

        this.customer = customer;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // TODO Auto-generated method stub
         Authentication auth = SecurityContextHolder.getContext().getAuthentication();
         if (auth != null) {

             return (Collection<GrantedAuthority>) auth.getAuthorities();
         }

        return null;
    }

    @Override
    public String getPassword() {

        return customer.getPassword();
    }

    @Override
    public String getUsername() {

        return customer.getEmailId();
    }

    @Override
    public boolean isAccountNonExpired() {

        return false;
    }

    @Override
    public boolean isAccountNonLocked() {

        return false;
    }

    @Override
    public boolean isCredentialsNonExpired() {

        return false;
    }

    @Override
    public boolean isEnabled() {

        return customer.isEnabled();
    }
}

我添加了一些System.out.print(),但发现我的UserAccountController无法访问。 CustomerDetailsService类也被访问,并且用户名正确传递。我该如何连接控制器?

解决方法

我建议使用Spring Security。看到这是您每次创建新应用程序时都会复制的代码,最好对其进行清理并让其框架正常工作。 ;)

首先,您对WebSecurityConfigurerAdapter的实现

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    private static final String USER_BY_USERNAME_QUERY = "select Email,Wachtwoord,Activatie from users where Email = ?" ;
    private static final String AUTHORITIES_BY_USERNAME_QUERY = "select Email,Toegang from users where Email = ?" ;

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;

    @Autowired
    private PasswordEncoder encoder;

    @Autowired
    private DataSource dataSource;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                    .antMatchers("/","/public/**","/css/**","/js/**","/font/**","/img/**","/scss/**","/error/**").permitAll()
                    .antMatchers("/mymt/**").hasAnyRole("MEMBER","ADMIN","GUEST","BOARD")
                    .antMatchers("/admin/**").hasAnyRole("ADMIN","BOARD")
                    .antMatchers("/support/**").hasAnyRole("ADMIN","BOARD")
                    .anyRequest().authenticated()
                .and()
                .formLogin()
                    .loginPage("/login")
                    .permitAll()
                .and()
                .logout()
                    .permitAll()
                .and()
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler)
                ;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
                .passwordEncoder(encoder)
                .dataSource(dataSource)
                .usersByUsernameQuery(USER_BY_USERNAME_QUERY)
                .authoritiesByUsernameQuery(AUTHORITIES_BY_USERNAME_QUERY)
                ;
    }
}

首先,我加载在主应用程序中定义为PasswordEncoder方法的@Bean。我使用BCryptPasswordEncoder进行密码哈希处理。

我从Spring Boot Starter的内存中加载了DataSource。为我用作默认数据库(我的默认持久性单元,因为我使用Spring Data jpa)配置了这个数据库

对于授权的配置,我首先禁用跨站点引用作为一种安全措施。然后,我配置所有路径,并告诉Spring谁可以访问Web应用程序的哪一部分。在我的数据库中,这些角色被记为ROLE_MEMBERROLE_BOARD,... ... Spring Security本身会丢弃ROLE_,但需要它存在。

此后,我添加formLogin并将其指向/login的URL,并允许所有角色访问登录页面。 我还添加了一些注销功能和异常处理。您可以根据需要将其忽略。

然后我配置身份验证。 在这里,我使用jdbcAuthentication通过数据库登录。 我给编码器提供密码,数据源,然后使用我预编译的两个查询,分别提供用户信息和用户角色。

就是这样。

我的控制器非常简单

@Controller
@RequestMapping("/login")
public class BasicLoginController {
    private static final String LOGON = "authentication/login";

    @GetMapping
    public String showLogin() {
        return LOGON;
    }
}

我的主菜单如下:

@SpringBootApplication
@EnableGlobalMethodSecurity(securedEnabled = true)
public class MyMT extends SpringBootServletInitializer {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(MyMT.class,args);
    }

    @Bean
    public BCryptPasswordEncoder encoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public Logger logger() {
        return Logger.getLogger("main");
    }

}

我的HTML页面如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>MyMT Login</title>
    <div th:insert="fragments/header :: header-css" />
</head>
<body>
<div class="bgMask">
    <div th:insert="fragments/header :: nav-header (active='Home')" />


    <main>
            <div class="container">
                <h1>Login</h1>
                <!-- Form -->
                <form class="text-center" style="color: #757575;" method="post">

                    <p>Om toegang te krijgen tot het besloten gedeelte moet je een geldige login voorzien.</p>
                    <div class="row" th:if="${param.error}">
                        <div class="col-md-3"></div>
                        <div class=" col-md-6 alert alert-danger custom-alert">
                            Invalid username and/or password.
                        </div>
                        <div class="col-md-3"></div>
                    </div>
                    <div class="row" th:if="${param.logout}">
                        <div class="col-md-3"></div>
                        <div class="col-md-6 alert alert-info custom-alert">
                            You have been logged out.
                        </div>
                        <div class="col-md-3"></div>
                    </div>

                    <!-- Name -->
                    <div class="md-form mt-3 row">
                        <div class="col-md-3"></div>
                        <div class="col-md-6">
                            <input type="text" id="username" class="form-control" name="username" required>
                            <label for="username">Email</label>
                        </div>
                        <div class="col-md-3"></div>
                    </div>

                    <!-- E-mai -->
                    <div class="md-form row">
                        <div class="col-md-3"></div>
                        <div class="col-md-6">
                            <input type="password" id="password" class="form-control" name="password" required>
                            <label for="password">Password</label>
                        </div>
                        <div class="col-md-3"></div>
                    </div>

                    <!-- Sign in button -->
                    <input type="submit" value="Login" name="login" class="btn btn-outline-info btn-rounded btn-block z-depth-0 my-4 waves-effect" />

                </form>
                <!-- Form -->
            </div>
    </main>

    <div th:insert="fragments/footer :: footer-scripts" />
    <div th:insert="fragments/footer :: footer-impl" />
</div>
</body>
</html>

在这里您可以看到两个输入字段,分别是用户名和密码名。

多数民众赞成在登录配置。现在,您可以使用所有控制器,而不必为其添加安全性。

用干净的代码术语。到处都增加安全性是一个横切关注点。 Spring安全通过使用面向方面的编程技巧来解决此问题。换一种说法。它拦截HttpRequest并首先检查用户。安全性会自动启动一个包含用户信息的会话,并对此会话进行检查。

我希望简短的说明有助于您进行登录。 :)

,
.loginPage("/login")

您已经在Spring Security中声明了login路径,因此Spring security将拦截您对该路径的调用,并且永远不会进入您的控制器。

所以您的控制器,都不是

public ModelAndView login(ModelAndView modelAndView,@RequestParam("emailID")String email,@RequestParam("password")String password)

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

将起作用。

您需要提供自己的身份验证提供程序,例如this。或者,您可以使用默认提供程序并提供UserDetailsService实现,例如this

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-