使用带注释的数据库登录Spring Security表单

时间:2014-07-12 10:43:38

标签: java spring spring-security

在内存身份验证中使用时,我有login page可正常工作。 但是,当我想使用jdbc authentication时,它不起作用,我无法理解为什么。

以下是我的App class

的代码
@EnableAutoConfiguration
@Configuration
@ComponentScan
public class App {

public static void main(String[] args) throws Throwable {
    SpringApplication.run(App.class, args);
}

@Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
    DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
    driverManagerDataSource.setDriverClassName("org.postgresql.Driver");
    driverManagerDataSource.setUrl("jdbc:postgresql://localhost:5432/bookDB");
    driverManagerDataSource.setUsername("postgres");
    driverManagerDataSource.setPassword("postgres");
    return driverManagerDataSource;
}

以下是我的Authentication class

的代码
@Configuration
@EnableWebMvcSecurity
public class Authentication extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/css/**").permitAll()
            .anyRequest().authenticated();

    http.formLogin().loginPage("/login").permitAll().and().csrf().disable()
            .logout().permitAll();

}

@Autowired
private DataSource dataSource;

public DataSource getDataSource() {
    return dataSource;
}

public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
}

@Override
protected void configure(AuthenticationManagerBuilder auth)
        throws Exception {
    auth.jdbcAuthentication()
            .dataSource(dataSource)
            .usersByUsernameQuery(
                    "select username,password, enabled from users where username=?");

}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

这里有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

我认为它缺少对方法的调用:authoritiesByUsernameQuery

您的代码变为:

@Override
protected void configure(AuthenticationManagerBuilder auth)
        throws Exception {
    auth.jdbcAuthentication()
            .dataSource(dataSource)
            .usersByUsernameQuery(
                    "select username, password, enabled from users where username=?")
          **.authoritiesByUsernameQuery(
                    "select username, role from user_roles where username = ?");** 
}