添加UsernamePasswordAuthenticationFilter时,身份验证失败

时间:2015-01-14 14:19:35

标签: spring spring-security

我使用的是Spring Security 3.2.5。 Bellow是我的安全配置类:


@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 security,则认证失败,否则它会顺利进行。有关此问题的任何建议吗? 我在日志文件中得到了这个:

  

2015-01-14 16:03:55,548 [io-8080-exec-54] DEBUG ProviderManager - 使用org.springframework.security.authentication.dao.DaoAuthenticationProvider进行身份验证尝试

     

2015-01-14 16:03:55,557 [io-8080-exec-54] DEBUG EntityManagerInvocationHandler - 为共享的EntityManager调用创建新的EntityManager

     

2015-01-14 16:03:5572 [io-8080-exec-54] DEBUG EntityManagerFactoryUtils - 关闭JPA EntityManager

     

2015-01-14 16:03:55,772 [io-8080-exec-54] DEBUG DaoAuthenticationProvider - User&#39;&#39;找不到

1 个答案:

答案 0 :(得分:0)

问题出在我的用户名和密码参数上。我声明了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;
}
相关问题