I am using spring security with spring boot with InMemoryAuthentication .
But my spring security configuration is now working as expected for Admin role.
Here are the relevant required details :
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);
}
}
With this configuration any endpoint which requires either "Admin" role or "User" role (i.e "/employee/getEmployee/**" and "/employee/getAllEmployees"
) are working fine with both "John" and "Mike" user.
But the endpoint which requires only"Admin" role (i.e "/employee/createEmployee", "/employee/createEmployees", "/employee/updateEmployee/**", "/employee/deleteEmployee/**"
) are not working with "John" who is configured to have "Admin" role and i am getting "Forbidden, status=403" error.
Need Help to access the endpoint which required only "Admin" role.
CodePudding user response:
I assume that this API will not be used by a web browser therefore you can disable csrf.
So I changed
@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();
}
to
@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();
}