添加 UsernamePasswordAuthenticationFilter 时身份验证失败

Authentication fails when add UsernamePasswordAuthenticationFilter

我正在使用 Spring 安全 3.2.5。下面是我的安全配置 class:


@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationProvider ap;
    @Autowired
    private UsernamePasswordAuthenticationFilter myFilter;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                    .formLogin()
                    .permitAll()
                    .and()
            .httpBasic();
        http.addFilterAfter(myFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Autowired
    public void configureGlobal(AuthenticationProvider ap, AuthenticationManagerBuilder amb) throws Exception {
        amb.authenticationProvider(ap);
    }

}

这是我声明的一些 bean:

@Bean
public UsernamePasswordAuthenticationFilter restApiAuthenticationFilter() {
    UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
    filter.setAuthenticationManager(authenticationManager());
    filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login", "POST"));
    return filter;
}

@Bean
public AuthenticationManager authenticationManager() {
    List<AuthenticationProvider> providers = new LinkedList<AuthenticationProvider>();
    providers.add(daoAuthenticationProvider());
    ProviderManager pm = new ProviderManager(providers);
    return pm;
}

现在的问题是,如果我将 UsernamePasswordAuthenticationFilter 添加到 spring 安全性,验证失败,否则一切顺利。关于这个问题有什么建议吗? 我在日志文件中得到这个:

2015-01-14 16:03:55,548 [io-8080-exec-54] DEBUG ProviderManager - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider

2015-01-14 16:03:55,557 [io-8080-exec-54] DEBUG EntityManagerInvocationHandler - Creating new EntityManager for shared EntityManager invocation

2015-01-14 16:03:55,672 [io-8080-exec-54] DEBUG EntityManagerFactoryUtils - Closing JPA EntityManager

2015-01-14 16:03:55,772 [io-8080-exec-54] DEBUG DaoAuthenticationProvider - User '' not found

问题出在我的用户名和密码参数上。我这样声明了 UsernamePasswordAuthenticationFilter bean,问题就解决了:

@Bean
public UsernamePasswordAuthenticationFilter restApiAuthenticationFilter() {
    UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
    filter.setAuthenticationManager(authenticationManager());
    filter.setUsernameParameter("username");
    filter.setPasswordParameter("password");
    filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login", "POST"));
    return filter;
}