title: Login in Spring security redirects to error Thymeleaf and Java based Configuration
body: <p>I am trying to implement Role based Authentication on my Spring Application. However, I get Redirected to <a href="http://localhost:8080/login?error=true" rel="nofollow noreferrer">http://localhost:8080/login?error=true</a> even if the credentials are right and hibernate fetches the login credentials without an issue.</p>
  
  <p>Here is my SecurityConfig class</p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
  
  @Autowired
  private UserDetailsService userDetailsService;
  
  @Autowired
  private BCryptPasswordEncoder bCryptPasswordEncoder;
  
  private static final String[] PUBLIC_MATCHERS = {
          "/css/**","/js/**","/image/**","/fonts/**","/webfonts/**","/register","/login","/actuator/**"
  };
  
  
  @Override
  protected void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests()        
          .antMatchers(PUBLIC_MATCHERS).permitAll().anyRequest().authenticated()
          .antMatchers("/addShipping").hasAuthority("ROLE_USER")
          .antMatchers("/item/add").hasAuthority("ROLE_ADMIN")
          .and().formLogin().loginPage("/login").failureUrl("/login?error=true").defaultSuccessUrl("/",true)
          .and()
              .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
              .logoutSuccessUrl("/")
              .deleteCookies("remember-me")
              .permitAll()
          .and().rememberMe()
          .and().exceptionHandling().accessDeniedPage("/denied");
  
  
    }
  
  @Override
    protected void configure(AuthenticationManagerBuilder auth)
        throws Exception {
        auth.userDetailsService(userDetailsService)
            .passwordEncoder(bCryptPasswordEncoder);
    }
  </code></pre>
  
  <p>Here is My login Controller</p>
  
  <pre><code>@RequestMapping(value = "/login", method = RequestMethod.GET) 
  public String login(Model model) { 
  
      return "login"; 
  }
  </code></pre>
  
  <p>My Role Class</p>
  
  <pre><code>@Data
  @Entity
  public class Role {
  
  @Id
  @Column(name="role_id")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  
  @NotNull
  @Column(name ="role")
  private String role;
  </code></pre>
  
  <p>}</p>
  
  <p>User Class</p>
  
  <pre><code>@Entity
  @Data
  public class User implements UserDetails {
  
  private static final long serialVersionUID = 1L;
  
  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  @Column(name ="user_id")
  private Long id;
  
  @OneToOne(cascade = CascadeType.ALL)
  private Cart cart;
  
  @OneToMany(mappedBy = "user")
  private List&lt;Order&gt; order;
  
  @NotEmpty(message="username is required")
  private  String username;
  
  @NotEmpty(message="password is required")
  private  String password;
  
  @NotEmpty(message="password is required")
  private  String fullname;
  
  private int enabled;
  
  @NotBlank(message="Pleace Provide your Role")
  private String role;
  
  
  @NotEmpty
  @Email 
  private String email;
  
  @NotEmpty(message="phone is required")
  private  String phone;
  
  @ManyToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER)
  @JoinTable( name="user_role", 
              joinColumns= {@JoinColumn(name="user_id")},
              inverseJoinColumns= {@JoinColumn(name="role_id")})
  private Set&lt;Role&gt; roles;
  
  @Override
  public Collection&lt;? extends GrantedAuthority&gt; getAuthorities() {
  
      Set&lt;GrantedAuthority&gt; authorities = roles
              .stream()
              .map(role -&gt; new SimpleGrantedAuthority(role.getRole()))
              .collect(Collectors.toSet());
  
  
      return authorities;
  }
  
  @Override
  public boolean isAccountNonExpired() {
      return true;
  }
  
  @Override
  public boolean isAccountNonLocked() {
      return true;
  }
  
  @Override
  public boolean isCredentialsNonExpired() {
      return true;
  }
  
  @Override
  public boolean isEnabled() {
      return true;
      }
  
  
  }
  </code></pre>
  
  <p>Login Template</p>
  
  <pre><code>                                &lt;div th:if="${param.error != null}" style="color: red;"&gt;Incorrect credentials&lt;/div&gt;
                                  &lt;form th:action="@{/login}" method="post"&gt;
                                      &lt;div class="form-group"&gt;&lt;input required="required" type="text" class="form-control" id="username" name="username" placeholder="Username" /&gt;&lt;/div&gt;
                                      &lt;div class="form-group"&gt; &lt;input required="required" type="password" class="form-control" id="password" name="password" placeholder="Password" /&gt;&lt;/div&gt;
                                      &lt;div class="col-sm-6 col-sm-offset-3 text-center"&gt;
                                          &lt;input type="checkbox" class="" name="remember" id="remember"&gt;
                                          &lt;label for="remember"&gt; Remember Me&lt;/label&gt;
                                      &lt;/div&gt;
  
                                      &lt;div class="col-sm-6 col-sm-offset-3"&gt; &lt;button  type="submit" class="btn btn-primary btn-block"&gt;Log in&lt;/button&gt; &lt;/div&gt;
                                  &lt;/form&gt;
  </code></pre>
  
  <p>[EDIT]</p>
  
  <p>User Service</p>
  
  <pre><code>public interface UserService extends UserDetailsService {
  
      void save(User user);
  
      User findUserByUsername(String username);
  
  }
  </code></pre>
  
  <p>User Sevice Implementation</p>
  
  <pre><code>@Service
  public class UserServicelmpl implements UserService {
  
    private BCryptPasswordEncoder bCryptPasswordEncoder;
  
    private UserRepository userRepository;
  
    private RoleRepository roleRepository;
  
  
  
    @Autowired
    public UserServicelmpl(UserRepository userRepository, RoleRepository 
  roleRepository, BCryptPasswordEncoder bCryptPasswordEncoder) {
      this.userRepository = userRepository;
      this.roleRepository = roleRepository;
      this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }
  
    @Override
    public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException {
      User user = userRepository.findByUsername(username);
  
      if (user != null) {
        return user;
      }
  
      throw new UsernameNotFoundException("The user with user name of '" + 
  username + "' is not found");
     }
  
    @Override
    public void save(User user) {
  
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        user.setEnabled(true);
        String Role = "ROLE_"+ user.getRole();
        Role userRole = roleRepository.findByRole(Role);
        user.setRoles(new HashSet&lt;Role&gt;(Arrays.asList(userRole)));
        userRepository.save(user);
  
    }
  
    @Override
      public User findUserByUsername(String username) {
        return userRepository.findByUsername(username);
      } 
  }
  </code></pre>
  
  <p><strong>[EDIT 2]</strong>
  Log </p>
  
  <p>o.s.s.a.dao.DaoAuthenticationProvider    : Authentication failed: password does not match stored value</p>
  
  <p>w.a.UsernamePasswordAuthenticationFilter : Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials</p>
  
  <p>org.springframework.security.authentication.BadCredentialsException: Bad credentials
      at org.springframework.security.authentication.dao.DaoAuthenticationProvider.additionalAuthenticationChecks(DaoAuthenticationProvider.java:93) ~[spring-security-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
      at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:166) ~[spring-security-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]</p>