0

我不需要管理員角色,所以我只需要執行身份驗證。未經授權的Spring Security JDBC身份驗證

@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()方法做。 問題是我該如何克服它?如何將默認角色分配給所有用戶而無需查詢數據庫?我如何才能使用登錄名和密碼登錄數據庫,並且沒有角色?

回答

4

選項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

+0

感謝您的幫助。現在第一個變體對我來說工作得很好。第二個看起來更好,我會試着實現它。 –