如何在Spring Security中使用hasRole?

时间:2018-10-15 22:43:58

标签: java spring security authentication authorization

我编写了通过Web登录表单进行身份验证的SpringBoot应用程序。类 WebSecurityController 负责身份验证和授权。 这是它的代码:

@Controller
@EnableWebSecurity
public class WebSecurityController extends WebSecurityConfiguration {

@Autowired
DataSource dataSource;

protected void configure(HttpSecurity http) throws Exception {
   http.authorizeRequests()
  .antMatchers("/users/getAll").access("hasRole('ROLE_ADMIN')")  
  .anyRequest().permitAll()
  .and()
    .formLogin().loginPage("/login")
    .usernameParameter("name").passwordParameter("password")
  .and()
    .logout().logoutSuccessUrl("/login?logout") 
   .and()
   .exceptionHandling().accessDeniedPage("/403")
  .and()
    .csrf();
 }

 @Autowired
 public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
     auth.jdbcAuthentication().dataSource(dataSource)
      .usersByUsernameQuery("select name,password,enabled from users where name=?")
      .authoritiesByUsernameQuery("select username, role from user_roles where username=?")
      .passwordEncoder(new BCryptPasswordEncoder());
 }

}

它从数据库的 users user_roles 表中检索用户凭据:

mysql> select * from users;
+----+--------+---------+---------+--------------------------------------------------------------+
| id | name   | salary  | enabled | password                                                     |
+----+--------+---------+---------+--------------------------------------------------------------+
|  1 | Rinat  |  100000 |       1 | $2a$10$Md.HmF6dVbwKLxcb09dgy.JTHKq3BLLg0ZrBHHx75fNmkH8.kGeGy |
|  2 | Juliya | 1000000 |       1 | $2a$10$XWksiqEwqJ4jWp00F37i/.A8YpknUPKi36kDd2NgwKI6EBPRRMzXa |
+----+--------+---------+---------+--------------------------------------------------------------+

mysql> select * from user_roles;
+----+----------+------------+
| id | username | role       |
+----+----------+------------+
|  1 | Rinat    | ROLE_ADMIN |
|  2 | Juliya   | ROLE_USER  |
+----+----------+------------+

身份验证可以正常工作,但是不幸的是,任何用户都可以访问受保护的资源“ / users / getAll”。似乎access("hasRole('ROLE_ADMIN')"无效。

2 个答案:

答案 0 :(得分:0)

我正在使用springboot 2.0.4.RELEASE春季安全性5.0.7.RELEASE,在我的WebSecurityController中,我使用的是方法:hasAuthority('ROLE_ADMIN')

这里是一个修复示例:

protected void configure(HttpSecurity http) throws Exception {
   http.authorizeRequests()
  // old
  //.antMatchers("/users/getAll").hasAuthority("ROLE_ADMIN") 
  //.anyRequest().permitAll() 
  // Update    
  .anyRequest().permitAll()
  .antMatchers("/users/getAll").hasAuthority("ROLE_ADMIN") 
  .and()
    .formLogin().loginPage("/login")
    .usernameParameter("name").passwordParameter("password")
  .and()
    .logout().logoutSuccessUrl("/login?logout") 
   .and()
   .exceptionHandling().accessDeniedPage("/403")
  .and()
    .csrf();
 }

答案 1 :(得分:0)

最后,我修复了方法configure()并从WebSecurityConfigurerAdapter扩展,如Spring Security参考文献6.4 Authorize Requests中所述:

@Controller
@EnableWebSecurity
public class WebSecurityController extends WebSecurityConfigurerAdapter {

@Autowired
DataSource dataSource;

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

     http
        .authorizeRequests()                                                                
            .antMatchers("/resources/**", "/signup", "/about").permitAll()                  
            .antMatchers("/users/**").hasRole("ADMIN")                                      
            .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")            
            .anyRequest().authenticated()                                                   
        .and()
            .formLogin()
        .and()
            .logout().logoutSuccessUrl("/login?logout") 
        .and()
            .exceptionHandling().accessDeniedPage("/403")
            ;
}

@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
     auth.jdbcAuthentication().dataSource(dataSource)
      .usersByUsernameQuery("select name,password,enabled from users where name=?")
      .authoritiesByUsernameQuery("select username, role from user_roles where username=?")
      .passwordEncoder(new BCryptPasswordEncoder());
} 

希望它对某人有帮助。纳德拉,谢谢!