Spring Security JDBC身份验证未经授权

时间:2016-04-21 16:31:34

标签: authentication jdbc spring-security authorization spring-java-config

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

@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 个答案:

答案 0 :(得分:7)

选项1 是设置具有静态角色的“虚拟”查询:

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界面。

相关问题