#java #spring-boot #spring-security #basic-authentication
Вопрос:
Я использую spring security с загрузкой spring с проверкой подлинности inMemoryAuthentication .
Но моя весенняя конфигурация безопасности теперь работает так, как ожидалось для роли администратора.
Вот соответствующие необходимые сведения :
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"
), отлично работает как с пользователем «Джон», так и с пользователем «Майк».
Но конечная точка, для которой требуется только роль»Администратор» ( i.e "/employee/createEmployee", "/employee/createEmployees", "/employee/updateEmployee/**", "/employee/deleteEmployee/**"
), не работает с «Джоном», у которого настроена роль «Администратор», и я получаю ошибку «Запрещено, статус=403».
Нужна помощь для доступа к конечной точке, для которой требуется только роль «Администратор».
Ответ №1:
Я предполагаю, что этот 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();
}