2016-05-08 6 views
1

私は、スプリングセキュリティ認証を統合テストしたかったのです。ログインするだけです。しかし、テスト中に次のエラーが登場:スプリングセキュリティテスト中のヌル認証

java.lang.AssertionError: Authentication should not be null 

マイカスタムUserDetailsS​​erviceがちょうどdatabseからユーザーを取得し、私のカスタムUserDetailsにマッピングされます。私はここで間違って何をしていますか?これは私が持っているほかに何かある:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = {Application.class}) 
@WebAppConfiguration 
public class SecurityConfigTest { 

    @Autowired 
    private WebApplicationContext context; 

    private MockMvc mockMvc; 

    @Before 
    public void setUp() throws Exception { 
     mockMvc = MockMvcBuilders 
      .webAppContextSetup(context) 
      .apply(springSecurity()) 
      .build(); 
    } 
    @Test 
    public void shouldAuthenticate() throws Exception { 
     mockMvc 
      .perform(formLogin()) 
      .andExpect(authenticated()); 
    } 
} 
@Configuration 
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    UserDetailsService userDetailsService; 

    @Override 
    public void configure(AuthenticationManagerBuilder auth) throws Exception { 
    auth 
      .userDetailsService(userDetailsService) 
      .passwordEncoder(new BCryptPasswordEncoder()); 
    } 
    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
    http 
      .httpBasic() 
      .and() 
      .authorizeRequests() 
       .antMatchers("/", "/login").permitAll() 
      .and() 
      .csrf().disable(); 
    } 
} 
@Configuration 
@EnableAutoConfiguration 
@ComponentScan 
public class Application extends SpringBootServletInitializer{ 
    @Override 
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 
     return application.sources(Application.class); 
    } 
    public static void main(String[] args) { 
     SpringApplication.run(Application.class, args); 
    } 
} 

答えて

2

としてはmockMvc.perform(formLogin())Spring Security Reference Manualで説明:

名 "ユーザー" と "/ログイン" へのPOSTを提出します、パスワード「パスワード」、および有効なCSRFトークンを含む。

だからあなたのログインURLが/loginない場合は、ユーザー名はuserない、またはパスワードがpasswordではありません、あなたはそれが動作することを期待してはいけません。

が実際にあなたのデータベースに存在するユーザーのユーザー名/パスワードの組み合わせを供給するために、あなたは mockMvc.perform(formLogin("/auth").user("admin").password("pass"))を使用することができるはずです(ログインURLを想定し、ユーザが adminという名前の、 /authで、パスワードは passです)。

詳細および例については、リファレンスマニュアルを参照してください。

+0

私はinMemoryAuthenticationを使って(ユーザー、パスワード...)、同じ問題を試しました。私はまた、SpringのセキュリティがそのログインPOST要求を自動的に処理していると考えました。そうでなければ、コントローラーはどのように見えますか? – HectorBarbossa

+0

ありがとうございました!私はそれを整理した。私はformLogin.loginPage()でそれを指定しておくべきです。 – HectorBarbossa

関連する問題