Spring安全JDBC未经授权的认证

Spring Security JDBC authentication without authorization

我不需要管理员角色,所以我只需要执行身份验证。

@Configuration
@EnableWebSecurity
protected static class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private MyAuthenticationSuccessHandler authenticationSuccessHandler;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage("/login")
                .successHandler(authenticationSuccessHandler).failureUrl("/login?error").permitAll().and().logout()
                .permitAll();
        http.csrf().disable();

    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("select login, password, enabled from users where login=?");

    }

}

我的问题是,当我尝试 运行 它时,我得到

org.springframework.security.authentication.InternalAuthenticationServiceException: PreparedStatementCallback; bad SQL grammar [select username,authority from authorities where username = ?]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'phonebook.authorities' doesn't exist

,这是合乎逻辑的,因为我没有应用 .authoritiesByUsernameQuery() 方法。 问题是我怎样才能克服它?如何在不需要查询数据库的情况下为所有用户分配默认角色?如何仅使用登录名和密码而不使用角色从数据库登录?

选项1是设置一个"dummy"具有静态角色的查询:

public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.jdbcAuthentication().dataSource(dataSource)
            .usersByUsernameQuery("select login, password, enabled from users where login=?")
            .authoritiesByUsernameQuery("select login, 'ROLE_USER' from users where login=?");
}

选项 2 如果您想优化第二个查询:

public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService);
}

您必须在其中实现 UserDetailsService 接口。