【发布时间】:2018-10-15 22:43:57
【问题描述】:
我编写了通过 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')" 似乎不起作用。
【问题讨论】:
标签: java spring security authentication authorization