Spring spring 引导中的安全配置不适用于管理员角色

Spring security configuration in spring boot not working for Admin role

我正在使用 spring 安全和 spring 引导 InMemoryAuthentication

但是我的 spring 安全配置现在可以正常工作 Admin 角色。

以下是所需的相关详细信息:

SecurityConfiguration.java

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("John").password("John").roles("Admin")
                .and()
                .withUser("Mike").password("Mike").roles("User")
                .and()
                .passwordEncoder(NoOpPasswordEncoder.getInstance());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/employee/createEmployee", "/employee/createEmployees", "/employee/updateEmployee/**", "/employee/deleteEmployee/**").hasRole("Admin")
                .antMatchers("/employee/getEmployee/**", "/employee/getAllEmployees").hasAnyRole("Admin", "User")
                .and().httpBasic();

    }
}

EmployeeResource.java

@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeResource {

    @Autowired
    EmployeeRepository employeeRepository;

    @GetMapping(path = "/greetEmployee", produces = MediaType.TEXT_PLAIN_VALUE)
    public String sayHello() {
        return "Hello Employee !!!";
    }

    @GetMapping(path = "/getAllEmployees", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
    public ResponseEntity<List<Employee>> getAllEmployee() {
        List<Employee> employeeList = employeeRepository.findAll();
        return new ResponseEntity<>(employeeList, HttpStatus.OK);
    }

    @GetMapping(path = "/getEmployee/{employeeId}", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
    public ResponseEntity<Employee> getEmployee(@PathVariable("employeeId") int employeeId) {
        Optional<Employee> optionalEmployee = employeeRepository.findByEmployeeId(employeeId);
        if (optionalEmployee.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>(optionalEmployee.get(), HttpStatus.FOUND);
    }

    @PostMapping(path = "/createEmployee", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
    public ResponseEntity<HttpStatus> createEmployee(@RequestBody Employee employee) {
        Random random = new Random();
        employee.setEmployeeId(random.nextInt(9999));
        employeeRepository.save(employee);
        log.info("Created employee with Id : {}", employee.getEmployeeId());

        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PostMapping(path = "/createEmployees", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
    public ResponseEntity<String> createEmployees(@RequestBody List<Employee> employeeList) {
        int count = 0;
        Random random = new Random();
        for (Employee employee : employeeList) {
            employee.setEmployeeId(random.nextInt(999999));
            employeeRepository.save(employee);
            log.info("Created employee with Id : {}", employee.getEmployeeId());
            count++;
        }
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("countOfObjectCreated", String.valueOf(count));
        return ResponseEntity.status(HttpStatus.CREATED).headers(responseHeaders).build();
    }

    @PutMapping(path = "/updateEmployee/{employeeId}", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
    public ResponseEntity<HttpStatus> updateCustomer(@PathVariable("employeeId") int employeeId, @RequestBody Employee employee) {
        Optional<Employee> optionalDbEmployee = employeeRepository.findByEmployeeId(employeeId);
        if (optionalDbEmployee.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        Employee dbEmployee = optionalDbEmployee.get();
        dbEmployee.setFirstName(employee.getFirstName());
        dbEmployee.setLastName(employee.getLastName());
        dbEmployee.setExtension(employee.getExtension());
        dbEmployee.setEmail(employee.getEmail());
        dbEmployee.setOfficeCode(employee.getOfficeCode());
        dbEmployee.setReportsTo(employee.getReportsTo());
        dbEmployee.setJobTitle(employee.getJobTitle());
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @DeleteMapping(path = "/deleteEmployee/{employeeId}")
    public ResponseEntity<HttpStatus> deleteCustomer(@PathVariable("employeeId") int employeeId) {
        employeeRepository.deleteById(employeeId);
        log.info("Employee with employee id {} Deleted successfully.", employeeId);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}

使用此配置,任何需要“管理员”角色或“用户”角色 (i.e "/employee/getEmployee/**" and "/employee/getAllEmployees") 的端点都可以与“John”和“Mike”用户一起正常工作。

但是只需要“管理员”角色 (i.e "/employee/createEmployee", "/employee/createEmployees", "/employee/updateEmployee/**", "/employee/deleteEmployee/**") 的端点无法与配置为具有“管理员”角色的“约翰”一起工作,我收到“禁止,状态=403”错误.

需要帮助才能访问只需要“管理员”角色的端点。

我假设此 API 不会被网络浏览器使用,因此您可以禁用 csrf。

所以我改变了

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/employee/createEmployee", "/employee/createEmployees", "/employee/updateEmployee/**", "/employee/deleteEmployee/**").hasRole("Admin")
                .antMatchers("/employee/getEmployee/**", "/employee/getAllEmployees").hasAnyRole("Admin", "User")
                .and().httpBasic();

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .csrf().disable()
                .antMatchers("/employee/createEmployee", "/employee/createEmployees", "/employee/updateEmployee/**", "/employee/deleteEmployee/**").hasRole("Admin")
                .antMatchers("/employee/getEmployee/**", "/employee/getAllEmployees").hasAnyRole("Admin", "User")
                .and().httpBasic();

    }