title: Spring Boot Security Login - "Wrong Credentials" Error
body: <p>I am trying to implement login and registration. Registering users works fine, but when I attempt to log in I keep getting Wrong Credentials error. Below is my code. I want users to log in with their email and password, so I'm really not sure if I'm missing something or if this is the way to go, because all tutorials out there show login examples using username and password. </p>
  
  <p>I am new to spring and still learning, so any help I get would be much appreciated.</p>
  
  <p>My WebSecurityConfig class:</p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  @ComponentScan(basePackageClasses = CustomUserDetailsService.class)
  public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
      @Autowired
      private UserDetailsService userDetailsService;
  
      @Autowired
      DataSource dataSource;
  
      @Autowired
      public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
          auth.userDetailsService(userDetailsService)
              .passwordEncoder(passwordEncoder());
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.authorizeRequests()
              .antMatchers("/test").authenticated()
              .and()
                  .formLogin()
                  .loginPage("/login")
                  .usernameParameter("email").passwordParameter("password")
                  .defaultSuccessUrl("/test")
                  .failureUrl("/login?error")
              .and()
                  .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/authentication/login")
                  .permitAll();
      }
  
      @Bean
      public BCryptPasswordEncoder passwordEncoder() {
          return new BCryptPasswordEncoder();
      }
  
      @Bean
      public PersistentTokenRepository persistentTokenRepository() {
          JdbcTokenRepositoryImpl tokenRepo = new JdbcTokenRepositoryImpl();
          tokenRepo.setDataSource(dataSource);
          return tokenRepo;
      }
  
      @Bean
      public UserDetailsService userDetailsService() {
          return super.userDetailsService();
      }
  }
  </code></pre>
  
  <p>CustomUserDetailsService</p>
  
  <pre><code>@Service
  public class CustomUserDetailsService implements UserDetailsService{
  
      private final UserRepository userRepository;
      private final RoleRepository roleRepository;
  
      @Autowired
      public CustomUserDetailsService(UserRepository userRepository, RoleRepository roleRepository) {
          this.userRepository = userRepository;
          this.roleRepository = roleRepository;
      }
      @Override
      public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
  
          User user = userRepository.findByEmail(email);
  
          if(user == null) {
              throw new UsernameNotFoundException("User not found" + email);
          }
          else {
              /*
              List&lt;String&gt; userRoles = roleRepository.findRoleByUserId(user.getUserId());
              return new CustomUserDetails(user, userRoles);
              */
              List&lt;Role&gt; roles = new ArrayList&lt;Role&gt;();
              roles.add(user.getRole());
              return new CustomUserDetails(user, roles);
          }
      }
  
  }
  </code></pre>
  
  <p>login.html</p>
  
  <pre><code>&lt;div th:if="${success}" class="alert alert-success" role="alert" th:text="${success}"&gt;&lt;/div&gt;
  &lt;div th:if="${error}" class="alert alert-danger" role="alert" th:text="${error}"&gt;&lt;/div&gt;
  
  
                      &lt;form method="post" th:action="@{/login}" th:object="${user}"&gt;
                        &lt;div class="form-group"&gt;
                          &lt;label for="exampleInputEmail1"&gt;Email address&lt;/label&gt;
                          &lt;input class="form-control" id="exampleInputEmail1" name="email" type="email" th:field="*{email}" aria-describedby="emailHelp" placeholder="Enter email"&gt;
                        &lt;/div&gt;
                        &lt;div class="form-group"&gt;
                          &lt;label for="exampleInputPassword1"&gt;Password&lt;/label&gt;
                          &lt;input class="form-control" id="exampleInputPassword1" name="password" type="password" th:field="*{password}" placeholder="Password"&gt;
                        &lt;/div&gt;
                        &lt;div class="form-group"&gt;
                          &lt;div class="form-check"&gt;
                            &lt;label class="form-check-label"&gt;
                              &lt;input class="form-check-input" type="checkbox" name="remember-me"&gt; Remember Password&lt;/label&gt;
                          &lt;/div&gt;
                        &lt;/div&gt;
                        &lt;button class="btn btn-primary btn-block" type="submit"&gt;Login&lt;/button&gt;
                      &lt;/form&gt;
  </code></pre>
  
  <p>Stack trace:</p>
  
  <pre><code>  .   ____          _            __ _ _
   /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
  ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
   \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
    '  |____| .__|_| |_|_| |_\__, | / / / /
   =========|_|==============|___/=/_/_/_/
   :: Spring Boot ::       (v1.5.10.RELEASE)
  
  2018-02-06 10:51:09.972  INFO 7116 --- [           main] c.b.app.SpringBootcampApplication        : Starting SpringBootcampApplication on localhost.localdomain with PID 7116 (started by cuteowl in /home/cuteowl/Documents/Work/JAVA SPRING PROJECT/SpringBootcamp)
  2018-02-06 10:51:09.975  INFO 7116 --- [           main] c.b.app.SpringBootcampApplication        : No active profile set, falling back to default profiles: default
  2018-02-06 10:51:10.287  INFO 7116 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@646be2c3: startup date [Tue Feb 06 10:51:10 CET 2018]; root of context hierarchy
  2018-02-06 10:51:11.704  INFO 7116 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$319d2e5a] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
  2018-02-06 10:51:12.285  INFO 7116 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
  2018-02-06 10:51:12.318  INFO 7116 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
  2018-02-06 10:51:12.320  INFO 7116 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.27
  2018-02-06 10:51:12.502  INFO 7116 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
  2018-02-06 10:51:12.502  INFO 7116 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2218 ms
  2018-02-06 10:51:12.743  INFO 7116 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
  2018-02-06 10:51:12.743  INFO 7116 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
  2018-02-06 10:51:12.743  INFO 7116 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
  2018-02-06 10:51:12.743  INFO 7116 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
  2018-02-06 10:51:12.745  INFO 7116 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
  2018-02-06 10:51:12.745  INFO 7116 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
  2018-02-06 10:51:13.419  INFO 7116 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
  2018-02-06 10:51:13.438  INFO 7116 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
      name: default
      ...]
  2018-02-06 10:51:13.592  INFO 7116 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.12.Final}
  2018-02-06 10:51:13.593  INFO 7116 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
  2018-02-06 10:51:13.594  INFO 7116 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
  2018-02-06 10:51:13.632  INFO 7116 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
  2018-02-06 10:51:13.739  INFO 7116 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
  2018-02-06 10:51:14.232  INFO 7116 --- [           main] org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000228: Running hbm2ddl schema update
  2018-02-06 10:51:14.243  INFO 7116 --- [           main] rmationExtractorJdbcDatabaseMetaDataImpl : HHH000262: Table not found: roles
  2018-02-06 10:51:14.244  INFO 7116 --- [           main] rmationExtractorJdbcDatabaseMetaDataImpl : HHH000262: Table not found: roles
  2018-02-06 10:51:14.412  INFO 7116 --- [           main] rmationExtractorJdbcDatabaseMetaDataImpl : HHH000262: Table not found: users
  2018-02-06 10:51:14.414  INFO 7116 --- [           main] rmationExtractorJdbcDatabaseMetaDataImpl : HHH000262: Table not found: users
  2018-02-06 10:51:15.429  INFO 7116 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
  2018-02-06 10:51:16.419  INFO 7116 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@54895681, org.springframework.security.web.context.SecurityContextPersistenceFilter@28daf506, org.springframework.security.web.header.HeaderWriterFilter@5a47730c, org.springframework.security.web.csrf.CsrfFilter@440ef8d, org.springframework.security.web.authentication.logout.LogoutFilter@4e48462d, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@633ddc0c, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@693f2213, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@7ac48f05, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@2dd0a0d0, org.springframework.security.web.session.SessionManagementFilter@1cde374, org.springframework.security.web.access.ExceptionTranslationFilter@46612bfc, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@3cc3f13e]
  2018-02-06 10:51:16.709  INFO 7116 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@646be2c3: startup date [Tue Feb 06 10:51:10 CET 2018]; root of context hierarchy
  2018-02-06 10:51:16.795  INFO 7116 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/login],methods=[GET]}" onto public java.lang.String com.bootcamp.app.controllers.LoginController.showLoginPage(org.springframework.ui.Model,com.bootcamp.app.models.User,java.util.Optional&lt;java.lang.String&gt;,java.util.Optional&lt;java.lang.String&gt;)
  2018-02-06 10:51:16.797  INFO 7116 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/register],methods=[GET]}" onto public java.lang.String com.bootcamp.app.controllers.RegisterController.showRegisterPage(org.springframework.ui.Model,com.bootcamp.app.models.User)
  2018-02-06 10:51:16.797  INFO 7116 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/register/new-user],methods=[POST]}" onto public java.lang.String com.bootcamp.app.controllers.RegisterController.postRegisterPage(org.springframework.ui.Model,com.bootcamp.app.models.User,org.springframework.validation.BindingResult,javax.servlet.http.HttpServletRequest)
  2018-02-06 10:51:16.797  INFO 7116 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/confirm],methods=[GET]}" onto public java.lang.String com.bootcamp.app.controllers.RegisterController.showConfirmationPage(org.springframework.ui.Model,java.lang.String)
  2018-02-06 10:51:16.797  INFO 7116 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/confirm],methods=[POST]}" onto public java.lang.String com.bootcamp.app.controllers.RegisterController.processConfirmationForm(org.springframework.ui.Model,java.util.Map)
  2018-02-06 10:51:16.798  INFO 7116 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/test],methods=[GET]}" onto public java.lang.String com.bootcamp.app.controllers.TestController.test()
  2018-02-06 10:51:16.801  INFO 7116 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity&lt;java.util.Map&lt;java.lang.String, java.lang.Object&gt;&gt; org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
  2018-02-06 10:51:16.802  INFO 7116 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
  2018-02-06 10:51:16.841  INFO 7116 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
  2018-02-06 10:51:16.842  INFO 7116 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
  2018-02-06 10:51:16.882  INFO 7116 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
  2018-02-06 10:51:17.394  INFO 7116 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
  2018-02-06 10:51:17.458  INFO 7116 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
  2018-02-06 10:51:17.465  INFO 7116 --- [           main] c.b.app.SpringBootcampApplication        : Started SpringBootcampApplication in 7.823 seconds (JVM running for 8.19)
  2018-02-06 10:51:35.719  INFO 7116 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
  2018-02-06 10:51:35.720  INFO 7116 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
  2018-02-06 10:51:35.748  INFO 7116 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 28 ms
  2018-02-06 10:51:47.792  INFO 7116 --- [nio-8080-exec-8] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
  2018-02-06 10:52:46.550  WARN 7116 --- [nio-8080-exec-8] o.s.s.c.bcrypt.BCryptPasswordEncoder     : Empty encoded password
  </code></pre>