Spring security4“访问被拒绝”问题,authorityByUsernameQuery不起作用?

时间:2017-08-26 23:00:29

标签: spring spring-boot spring-security

我有一个表代理: [id主键,电子邮件varchar,密码varchar]

和agents_roles表: [agent_role_id主键,电子邮件varchar,agent_id外键]

在我的安全控制器中,我有:

@Configuration

@EnableWebSecurity

public class Security extends WebSecurityConfigurerAdapter {

     @Autowired
     private DataSource dataSource;

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

            auth.jdbcAuthentication().dataSource(dataSource)
                             .usersByUsernameQuery("select email, password,visibility from agents where email=?")
                             .authoritiesByUsernameQuery("select email, role from agents_roles where email=?");
      }

      @Override
      protected void configure(HttpSecurity http) throws Exception {

            http.formLogin().loginPage("/login");

         http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN");

           http.authorizeRequests().antMatchers("/agent/**").hasRole("DEV");

           http.exceptionHandling().accessDeniedPage("/403");

     }

}

当我尝试获取主页时,获取访问被拒绝页面“403.html”!

我认为第二个查询“authoritiesByUsernameQuery”无法正常工作,但我不知道为什么?

我尝试了另一个用户表和users_role的例子,它运行正常,但区别在于用户名是主键!!

请帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

我发现了问题!

在我的查询中,我使用它并且它工作正常:

 ....
 usersByUsernameQuery("select a.email as username, a.password, a.visibility from agents a where a.email=?")
                             .authoritiesByUsernameQuery("select ar.email as username, ar.role from agents_roles ar, agents a where a.id = ar.agent_id and ar.email=?");
 ....