title: Authentication failed (Bad Credentuals) in Spring Security with hibernate for REST
body: <p>I've created a spring boot app with spring-data-rest.</p>
  
  <p>My Rest API is working just fine. Then I imported the spring security. I've also done configurations after referring to a number of Web resources. </p>
  
  <p>However, each time I send a request, I get Bad Credential Error  The below are my codes</p>
  
  <h2>User.java</h2>
  
  <pre><code>package com.innaun.model;
  
  import org.springframework.data.rest.core.annotation.RestResource;
  
  import javax.persistence.*;
  import javax.validation.constraints.NotNull;
  import java.util.HashSet;
  import java.util.Set;
  
  @Entity
  public class User {
  
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private Long userId;
  
      @Column(unique = true, nullable = false)
      private String username;
  
      @NotNull
      @RestResource(exported = false  )
      private String password;
  
      @NotNull
      private boolean enabled;
  
      @OneToMany
      private Set&lt;UserRole&gt; userRoles = new HashSet&lt;UserRole&gt;(0);
  
      public User() {
      }
  
      public User(String username, String password, boolean enabled) {
          this.username = username;
          this.password = password;
          this.enabled = enabled;
      }
  
      public Set&lt;UserRole&gt; getUserRoles() {
          return userRoles;
      }
  
      public void setUserRoles(Set&lt;UserRole&gt; userRoles) {
          this.userRoles = userRoles;
      }
  
      public Long getUserId() {
          return userId;
      }
  
      public void setUserId(Long userId) {
          this.userId = userId;
      }
  
      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 boolean isEnabled() {
          return enabled;
      }
  
      public void setEnabled(boolean enabled) {
          this.enabled = enabled;
      }
  }
  </code></pre>
  
  <h2>UserRole.java</h2>
  
  <pre><code>package com.innaun.model;
  
  import javax.persistence.*;
  import javax.validation.constraints.NotNull;
  
  @Entity
  public class UserRole {
  
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private Long userRoleId;
  
      @NotNull
      private String userRole;
  
      @ManyToOne
      private User user;
  
      public UserRole() {
      }
  
      public UserRole(String userRole, User user) {
          this.userRole = userRole;
          this.user = user;
      }
  
      public Long getUserRoleId() {
          return userRoleId;
      }
  
      public void setUserRoleId(Long userRoleId) {
          this.userRoleId = userRoleId;
      }
  
      public String getUserRole() {
          return userRole;
      }
  
      public void setUserRole(String userRole) {
          this.userRole = userRole;
      }
  
      public User getUser() {
          return user;
      }
  
      public void setUser(User user) {
          this.user = user;
      }
  }
  </code></pre>
  
  <h2>UserRepository.java</h2>
  
  <pre><code>package com.innaun.model;
  
  import org.springframework.data.repository.CrudRepository;
  import org.springframework.data.repository.query.Param;
  import org.springframework.data.rest.core.annotation.RepositoryRestResource;
  
  @RepositoryRestResource
  public interface UserRepository extends CrudRepository&lt;User, Long&gt;{
      User findByUsername(@Param("user") String user);
  }
  </code></pre>
  
  <h2>UserRoleRepository.java</h2>
  
  <pre><code>package com.innaun.model;
  
  import org.springframework.data.repository.CrudRepository;
  import org.springframework.data.rest.core.annotation.RepositoryRestResource;
  
  @RepositoryRestResource
  public interface UserRoleRepository extends CrudRepository&lt;UserRole, Long&gt; {
  }
  </code></pre>
  
  <h2>AppUserDetailsService.java</h2>
  
  <pre><code>package com.innaun.model;
  
  import com.innaun.model.UserRepository;
  import com.innaun.model.UserRole;
  import org.springframework.security.core.GrantedAuthority;
  import org.springframework.security.core.authority.SimpleGrantedAuthority;
  import org.springframework.security.core.userdetails.User;
  import org.springframework.beans.factory.annotation.Autowired;
  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;
  
  import javax.transaction.Transactional;
  import java.util.ArrayList;
  import java.util.HashSet;
  import java.util.List;
  import java.util.Set;
  
  @Service("appUserDetailsService")
  public class AppUserDetailsService implements UserDetailsService {
  
      @Autowired
      private UserRepository userRepository;
  
  
      @Transactional
      @Override
      public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
          com.innaun.model.User user = userRepository.findByUsername(s);
  
          List&lt;GrantedAuthority&gt; authorities = buildUserAuthority(user.getUserRoles());
  
          return buildUserForAuthentication(user, authorities);
      }
  
      private User buildUserForAuthentication(com.innaun.model.User user, List&lt;GrantedAuthority&gt; authorities){
                  return new User(user.getUsername(), user.getPassword(), user.isEnabled(), true, true, true, authorities);
      }
  
      private List&lt;GrantedAuthority&gt; buildUserAuthority(Set&lt;UserRole&gt; userRoles){
          Set&lt;GrantedAuthority&gt; setAuths = new HashSet&lt;GrantedAuthority&gt;();
  
          for (UserRole userRole : userRoles){
              setAuths.add(new SimpleGrantedAuthority(userRole.getUserRole()));
          }
  
          List&lt;GrantedAuthority&gt; result = new ArrayList&lt;GrantedAuthority&gt;(setAuths);
  
          return result;
      }
  
  
  }
  </code></pre>
  
  <h2>ApplicationRESTSecurity.java</h2>
  
  <pre><code>package com.innaun;
  
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.beans.factory.annotation.Qualifier;
  import org.springframework.context.annotation.Bean;
  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.core.userdetails.UserDetailsService;
  import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  import org.springframework.security.crypto.password.PasswordEncoder;
  
  
  @Configuration
  @EnableWebSecurity
  public class ApplicationRESTSecurity extends WebSecurityConfigurerAdapter {
  
      @Qualifier("appUserDetailsService")
      @Autowired
      UserDetailsService userDetailsService;
  
      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
          auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
      }
  
      @Bean
      public PasswordEncoder passwordEncoder() {
          PasswordEncoder encoder = new BCryptPasswordEncoder();
          return encoder;
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http
                  .authorizeRequests()
                  .anyRequest().fullyAuthenticated()
                  .and().httpBasic()
                  .and().csrf()
                  .disable();
      }
  }
  </code></pre>
  
  <p>Also, I've added the below to add a test user to the database</p>
  
  <pre><code>package com.innaun;
  
  import com.innaun.model.User;
  import com.innaun.model.UserRepository;
  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 PitchuApplication {
  
      public static void main(String[] args) {
          SpringApplication.run(PitchuApplication.class, args);
      }
  
      @Bean
      CommandLineRunner init(UserRepository userRepository) {
  
          return (args) -&gt; {
              userRepository.save(new User("myuser", "mypassword", true));
          };
      }
  
  }
  </code></pre>
  
  <p>Just as I thought, the database now has the above user and the user is enabled.</p>
  
  <p><a href="https://i.stack.imgur.com/VNEJ6.png" rel="nofollow noreferrer">Screenshot of the User data table</a></p>
  
  <p>All the other tables are blank.</p>
  
  <p>However when I tried the curl </p>
  
  <pre><code>curl -u myuser:mypassword localhost:8080
  </code></pre>
  
  <p>it returned</p>
  
  <pre><code>{"timestamp":1489090315435,"status":401,"error":"Unauthorized","message":"Bad credentials","path":"/"}
  </code></pre>
  
  <p>Can anyone explain where did I went wrong.</p>