我是一个新手,正在学习spring-boot和spring security,在这里我尝试创建一个EmployeeManagement应用程序,它可以对员工执行CRUD操作。在这个应用程序中,管理员应该能够动态地将用户添加到数据库中,管理员应该具有访问所有API的权限,而用户应该仅具有查看员工的权限。我创建了所需的一切,在添加spring security之前,我的项目运行良好,但在添加它之后,我的用户和管理员能够登录,但不能访问任何API。它显示错误403禁止,我不明白为什么spring安全没有按照configure(http安全)方法中提到的角色授予访问URL的权限(在本项目中,我使用了MySQl数据库、spring引导、spring安全和swagger-ui)
这是我的安全配置
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(encodePWD());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/secure/**").hasRole("ADMIN").and().authorizeRequests()
.antMatchers("/", "/employees/save", "/employees/updateEmployee/{id}", "/employees/deleteEmployee/{id}")
.hasRole("ADMIN").and().authorizeRequests()
.antMatchers("/", "/employees/list", "/employees/getEmployee/{id}",
"/employees/getAllEmployeesWithTheseName/{firstname}",
"/employees/getEmployeesCustomSortedByName/{direction}")
.hasAnyRole("ADMIN", "USER")
.and()
.httpBasic().and().formLogin().loginProcessingUrl("/login")
.defaultSuccessUrl("/swagger-ui.html", true).and().cors().and().csrf().disable();
}
@Bean
public BCryptPasswordEncoder encodePWD() {
return new BCryptPasswordEncoder();
}
}
这是我收到的错误
{
"timestamp": "2022-11-07T15:59:26.930+00:00",
"status": 403,
"error": "Forbidden",
"message": "Forbidden",
"path": "/EmployeeManagement/employees/list"
}
1条答案
按热度按时间yduiuuwa1#
不能在
antMatchers(....)
中使用PathVariable
来自文档AntPathMatcher
Map使用以下规则匹配URL:
***与路径中的零个或多个目录匹配
*{spring:[a-z]+}将正则表达式[a-z]+匹配为名为“spring”的路径变量
因此用途:
"/employees/getEmployee/{id:[0-9]+}"
或"/employees/getEmployee/*
"/employees/getAllEmployeesWithTheseName/{firstname:[A-Za-z]+}"
或"/employees/getAllEmployeesWithTheseName/*