title: Spring Boot Security with Database Users not logging in
body: <p>I have tried everything I can think of to get this working. I've tried the techniques in my books, countless online tutorials and examples, and no matter what I do I am not having success. I have been trying to figure this out for weeks now.</p>
  
  <p>This is the closest I have gotten. I get prompted with the login page when I try to access the /users GetMapping, as expected, but I get a 403 forbidden error after entering credentials, so I believe my credentials are correct and perhaps there is some sort of problem with the role? I have already disabled csrf as per the suggestions on other stack overflow answers. I am getting a bit desperate and I apologize for my ignorance. Here is what I currently have (this implementation is from one of my books)</p>
  
  <p>Note: All of the components and functionality work properly when I remove the security classes and dependencies. I am at a loss. If you can help I would be forever grateful.</p>
  
  <p>Main application:</p>
  
  <pre><code>package com.madhax.website;
  
  import com.madhax.website.domain.Article;
  import com.madhax.website.domain.User;
  import com.madhax.website.service.ArticleService;
  import com.madhax.website.service.UserService;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.boot.CommandLineRunner;
  import org.springframework.boot.SpringApplication;
  import org.springframework.boot.autoconfigure.SpringBootApplication;
  import org.springframework.context.annotation.Bean;
  
  @SpringBootApplication
  public class WebsiteApplication {
  
      @Autowired
      private UserService userService;
  
      @Autowired
      private ArticleService articleService;
  
      public static void main(String[] args) {
          SpringApplication.run(WebsiteApplication.class, args);
      }
  
      @Bean
      CommandLineRunner runner() {
          return args -&gt; {
  
              User myUser = new User(
                      "admin",
                      "$2a$04$C/mOkKfXtOhKjhnUUrwp3OcWzLHJqkGzYpV1oys.MBPXc9M8soAQ6",
                      "USER");
              myUser.setFirstName("James");
              myUser.setLastName("Cathcart");
              userService.saveUser(myUser);
  
              Article article1 = new Article(
                      "Example Article 1 Title",
                      "Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora " +
                      "torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, " +
                      "urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis " +
                      "turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus " +
                      "consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices.",
                      myUser);
              articleService.saveArticle(article1);
  
              Article article2 = new Article(
                      "Example Article 1 Title",
                      "Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora " +
                              "torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, " +
                              "urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis " +
                              "turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus " +
                              "consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices.",
                      myUser);
              articleService.saveArticle(article2);
  
              Article article3 = new Article(
                      "Example Article 1 Title",
                      "Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora " +
                              "torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, " +
                              "urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis " +
                              "turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus " +
                              "consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices.",
                      myUser);
              articleService.saveArticle(article3);
  
              Article article4 = new Article(
                      "Example Article 1 Title",
                      "Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora " +
                              "torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, " +
                              "urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis " +
                              "turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus " +
                              "consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices.",
                      myUser);
              articleService.saveArticle(article4);
  
          };
      }
  }
  </code></pre>
  
  <p>SecurityConfig:</p>
  
  <pre><code>package com.madhax.website.config;
  
  import com.madhax.website.service.UserDetailServiceImpl;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.context.annotation.Configuration;
  import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  
  @Configuration
  @EnableWebSecurity
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
  
      @Autowired
      private UserDetailServiceImpl userDetailsService;
  
      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http
                  .csrf().disable()
                  .authorizeRequests()
                  .antMatchers("/users", "/users/**")
                      .hasRole("USER")
                  .antMatchers("/", "/**").permitAll()
                  .and()
                      .formLogin();
      }
  }
  </code></pre>
  
  <p>UserDetailServiceImpl</p>
  
  <pre><code>package com.madhax.website.service;
  
  import com.madhax.website.domain.User;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.security.core.authority.AuthorityUtils;
  import org.springframework.security.core.userdetails.UserDetails;
  import org.springframework.security.core.userdetails.UserDetailsService;
  import org.springframework.security.core.userdetails.UsernameNotFoundException;
  import org.springframework.stereotype.Service;
  
  @Service
  public class UserDetailServiceImpl implements UserDetailsService {
  
      @Autowired
      private UserRepository userRepository;
  
      @Override
      public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
          User currentUser = userRepository.findByUsername(username);
          UserDetails user = new org.springframework.security.core.userdetails.User(
                  username,
                  currentUser.getPassword(),
                  true,
                  true,
                  true,
                  true,
                  AuthorityUtils.createAuthorityList(currentUser.getRole()));
          return user;
      }
  }
  </code></pre>
  
  <p>UserRepository:</p>
  
  <pre><code>package com.madhax.website.service;
  
  import com.madhax.website.domain.User;
  import org.springframework.data.repository.CrudRepository;
  
  public interface UserRepository extends CrudRepository&lt;User, Long&gt; {
      public User findByUsername(String username);
  }
  </code></pre>
  
  <p>UserService:</p>
  
  <pre><code>package com.madhax.website.service;
  
  import com.madhax.website.domain.User;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.stereotype.Service;
  
  import java.util.List;
  import java.util.Optional;
  
  @Service
  public class UserService {
  
      @Autowired
      UserRepository userRepository;
  
      public List&lt;User&gt; getAllUsers() {
          return (List&lt;User&gt;) userRepository.findAll();
      }
  
      public Optional&lt;User&gt; getUserById(long id) {
          return userRepository.findById(id);
      }
  
      public void saveUser(User user) {
          userRepository.save(user);
      }
  
      public void deleteUser(User user) {
          userRepository.delete(user);
      }
  }
  </code></pre>
  
  <p>User:</p>
  
  <pre><code>package com.madhax.website.domain;
  
  import javax.persistence.Entity;
  import javax.persistence.GeneratedValue;
  import javax.persistence.GenerationType;
  import javax.persistence.Id;
  
  @Entity
  public class User {
  
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private Long id;
      private String username;
      private String password;
      private String firstName;
      private String lastName;
      private String role;
  
      public User() { }
  
      public User(String username, String password, String role) {
          this.username = username;
          this.password = password;
          this.role = role;
      }
  
      public Long getId() {
          return id;
      }
  
      public void setId(Long id) {
          this.id = id;
      }
  
      public String getUsername() {
          return username;
      }
  
      public void setUsername(String username) {
          this.username = username;
      }
  
      public String getPassword() {
          return password;
      }
  
      public void setPassword(String password) {
          this.password = password;
      }
  
      public String getFirstName() {
          return firstName;
      }
  
      public void setFirstName(String firstName) {
          this.firstName = firstName;
      }
  
      public String getLastName() {
          return lastName;
      }
  
      public void setLastName(String lastName) {
          this.lastName = lastName;
      }
  
      public String getRole() {
          return role;
      }
  
      public void setRole(String role) {
          this.role = role;
      }
  }
  </code></pre>