首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我的Spring自定义登录表单不起作用[更新]

我的Spring自定义登录表单不起作用[更新]
EN

Stack Overflow用户
提问于 2020-08-21 14:03:46
回答 2查看 1K关注 0票数 7

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

因此,我已经开发了注册功能,它运行良好。

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

我正在使用Eclipse。

下面是Controller类:WebMvcConfiguration.java

代码语言:javascript
复制
@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

代码语言:javascript
复制
@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", method= {RequestMethod.GET, 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

代码语言:javascript
复制
@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

代码语言:javascript
复制
<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

代码语言:javascript
复制
<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> 

编辑

新的UserDetailsService类:

代码语言:javascript
复制
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类,并且用户名正在正确传递。如何将控制器与此连接?

EN

回答 2

Stack Overflow用户

发布于 2020-10-06 05:43:22

我推荐的是使用Security。看到这是您每次创建新应用程序时都要复制的代码,最好是清理它,让框架完成它的工作。;)

首先,您的WebSecurityConfigurerAdapter实现

代码语言:javascript
复制
@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的内存中加载我的DataSource。这个是为我使用的默认数据库配置的(我的默认持久性单元,因为我使用Spring )

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

之后,我添加formLogin并将其指向/login的url,并允许所有角色访问登录页面。我还添加了一些注销功能和异常处理。如果你想的话,你可以把这些忘了。

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

实际上就是这样。

我的控制器很简单

代码语言:javascript
复制
@Controller
@RequestMapping("/login")
public class BasicLoginController {
    private static final String LOGON = "authentication/login";

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

我的主菜是这样的:

代码语言:javascript
复制
@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页面如下所示:

代码语言:javascript
复制
<!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并首先检查用户。安全性使用用户信息自动启动会话,并对此会话进行检查。

我希望简短的解释有助于让你的登录工作。:)

票数 2
EN

Stack Overflow用户

发布于 2020-10-06 06:30:31

代码语言:javascript
复制
.loginPage("/login")

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

所以你的控制器,也不是

代码语言:javascript
复制
public ModelAndView login(ModelAndView modelAndView, @RequestParam("emailID")String email, @RequestParam("password")String password)

代码语言:javascript
复制
 @GetMapping("/login")
    public String login() {
      return "login";
    }

会起作用的。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63524355

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档