首页 > 解决方案 > 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 错误,一切正常。

标签: reactjsspring-bootjwt

解决方案


推荐阅读