reactjs - Spring boot + JWT + Reactjs:POST API 出现 403 错误
问题描述
我需要一些帮助。我尝试使用 JWT 令牌将图像文件从 Reactjs 发送到 Spring Boot 后端,但我不断收到 403 错误:如果我在 WebSecurityConfig 中的 URL 上添加 hasRole(),它只会引发 403 错误。在我的控制器中,我有两种方法(empProfileImageUpload()、getAllEmployee())。我尝试访问 getAllEmployee() 方法以在 WebSecurityConfig 中启用具有 hasRole() 的所有员工,它可以找到,但它不适用于 empProfileImageUpload() 方法。
@Configurable
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().and().csrf().disable()
.authorizeRequests()
.antMatchers("/employee/add_employee").permitAll()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilter(new JwtUsernameAndPasswordAuthFilter(authenticationManager(), securityKey, secretKey, authRepository, passwordEncoder()))
.addFilterAfter(new JwtAuthVerifier(securityKey, secretKey), JwtUsernameAndPasswordAuthFilter.class)
.authorizeRequests()
.antMatchers("/employee/**").hasRole(ADMIN.name())
.antMatchers("/auth_management/**").hasRole(ADMIN.name())
.anyRequest()
.authenticated();
}
}
如果我将此行.antMatchers("/auth_management/ ").hasRole(ADMIN.name()) 更改为此 .antMatchers("/auth_management/ ").permitAll(),它可以正常查找而不会出现任何错误。
控制器类
@RestController
@RequestMapping("/auth_management")
@CrossOrigin("*")
public class ManagementController {
private final EmployeeServiceManagement empServiceManagement;
@Autowired
public ManagementController(EmployeeServiceManagement emServiceManagement) {
this.empServiceManagement = emServiceManagement;
}
@PostMapping(
path = "{employeeID}/upload_file",
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
public void empProfileImageUpload(@PathVariable("employeeID") Long employeeID,
@RequestParam("file") MultipartFile file) {
empServiceManagement.uploadEmpProfileImage(employeeID, file);
}
@GetMapping(value = "/find_all_employees")
public List<Employee> getAllEmployee(@ModelAttribute Employee employee, Model model) {
return empServiceManagement.getAll();
}
}
仅当我尝试访问 empProfileImageUpload() 方法时,我才会收到 403 错误,当我尝试访问getAllEmployee ( )方法时它会起作用。而且我将.antMatchers("/auth_management/ ").hasRole(ADMIN.name()) 替换为 .antMatchers("/auth_management/ ").permitAll()我没有收到 403 错误,一切正常。
解决方案
推荐阅读
- ruby-on-rails - 从实例更新或保存记录
- jquery - 禁用输入的标签未分配给 Jquery 中的属性
- javascript - 如何在具有视差效果的滚动时禁用(不隐藏)滚动垂直条
- ruby-on-rails - 如何在活动记录查询中使用正则表达式?
- java - java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException 启动 Tomcat 服务器时
- python - 如何检查表单是否不包含任何数据
- c# - PInvoke c++ dll 使堆栈不平衡
- c# - 读入 DataTable 时的列类型
- python - 每次迭代后将列表中的值存储到数组中包含python中的指定文件列
- php - 如何在 laravel .env 文件中配置发件人邮件地址