如何在Spring Security中使用hasRole? [英] How to use hasRole in Spring Security?

查看:505
本文介绍了如何在Spring Security中使用hasRole?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wrote SpringBoot application with authentication via web login form. Class WebSecurityController is responsible for authentication and authorization. Here is its code:

@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 表中检索用户凭据:

It retrieves the user credentials from users and user_roles tables of the database:

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')" 无效.

Authentication works fine, but unfortunately any users can access to protected resource "/users/getAll". It seems that access("hasRole('ROLE_ADMIN')" not working.

推荐答案

最后,我修复了方法 configure()并从 WebSecurityConfigurerAdapter 扩展了该功能,如Spring Security参考中所述 6.4授权请求:

Finally I repair the method configure() and extends from WebSecurityConfigurerAdapter as it said in Spring Security reference 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());
} 

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

Hope it helps somebody. Nadra, thanks!

这篇关于如何在Spring Security中使用hasRole?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆