title: "An Authentication object was not found in the SecurityContext" - UserDetailsService Setup in Spring Boot
body: <p>In a Spring Boot application, I have an in-memory Spring Security setup. And it works as desired. </p>
  
  <pre><code>@Configuration
  @EnableGlobalMethodSecurity(prePostEnabled = true)
  class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
      auth.inMemoryAuthentication()
              .withUser("kevin").password("password1").roles("USER").and()
              .withUser("diana").password("password2").roles("USER", "ADMIN");
    }
  
    @Override
    protected void configure(HttpSecurity http) throws Exception {
  
      http
              .httpBasic().and()
              .authorizeRequests()
              .antMatchers(HttpMethod.POST, "/foos").hasRole("ADMIN")
              .antMatchers(HttpMethod.PUT, "/foos/**").hasRole("ADMIN")
              .antMatchers(HttpMethod.PATCH, "/foos/**").hasRole("ADMIN")
              .antMatchers(HttpMethod.DELETE, "/foos/**").hasRole("ADMIN")
              .and()
              .csrf().disable();
    }
  }
  </code></pre>
  
  <p>Now, I convert it to a database based approach with the following code.</p>
  
  <pre><code>@Entity
  class Account {
  
    enum Role {ROLE_USER, ROLE_ADMIN}
  
    @Id
    @GeneratedValue
    private Long id;
  
    private String userName;
  
  //  @JsonIgnore
    private String password;
  
    @ElementCollection(fetch = FetchType.EAGER)
    Set&lt;Role&gt; roles = new HashSet&lt;&gt;();
     ...
  }
  </code></pre>
  
  <p>The repository:</p>
  
  <pre><code>@RepositoryRestResource
  interface AccountRepository extends CrudRepository&lt;Account, Long&gt;{
  
    @PreAuthorize("hasRole('USER')")
    Optional&lt;Account&gt; findByUserName(@Param("userName") String userName);
  }
  </code></pre>
  
  <p>The UserDetailsService:</p>
  
  <pre><code>@Component
  class MyUserDetailsService implements UserDetailsService {
  
    private AccountRepository accountRepository;
  
    MyUserDetailsService(AccountRepository accountRepository){
      this.accountRepository = accountRepository;
    }
  
    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
      Optional&lt;Account&gt; accountOptional = this.accountRepository.findByUserName(name);
      if(!accountOptional.isPresent())
          throw new UsernameNotFoundException(name);
  
      Account account = accountOptional.get();
      return new User(account.getUserName(), account.getPassword(),
          AuthorityUtils.createAuthorityList(account.getRoles().stream().map(Account.Role::name).toArray(String[]::new)));
    }
  }
  </code></pre>
  
  <p>And the modification of the WebSecurityConfigurerAdapter configuration:</p>
  
  <pre><code>@Configuration
  @EnableGlobalMethodSecurity(prePostEnabled = true)
  class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  
    private MyUserDetailsService userDetailsService;
  
    SecurityConfiguration(MyUserDetailsService userDetailsService){
      this.userDetailsService = userDetailsService;
    }
  
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
      auth.userDetailsService(userDetailsService);  // &lt;-- replacing the in-memory anthentication setup
    }
    ...
  }
  </code></pre>
  
  <p>When I send the same request with <strong>a pair of username and password as the basic authentication</strong> as for the in-memory version, I, however, get the 401 error:</p>
  
  <pre><code>{
    "timestamp": 1489430818803,
    "status": 401,
    "error": "Unauthorized",
    "message": "An Authentication object was not found in the SecurityContext",
    "path": "/foos"
  }
  </code></pre>
  
  <p>After reading through some related document and sample code, I can't see the cause of the error. What the error message says is that the user isn't in the Spring Security context. The line of AuthenticationManagerBuilder usage in the  userDetailsService(userDetailsService) shall take care of setting up these users in the SecurityContext, isn't it?</p>
  
  <p>The Spring Boot version is 1.4.3.RELEASE.</p>