I have a website based on spring boot, spring-security, thymeleaf, I also use ajax in some cases.
Issue: I am using form login security in spring security. In the browser, after I login I can consume rest API (GET), but using Ajax, it returns a http 403 error, even if my Ajax request contains session id in cookies.
Security config:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/rest/**").hasRole("ADMIN")
.anyRequest().permitAll()
.and()
.formLogin().loginPage("/sign-in-up")
.loginProcessingUrl("/signInProcess").usernameParameter("phone").and().logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/");
}
REST API I test it correctly:
@RestController
@RequestMapping("rest/categories")
public class CategoriesRest {
@Autowired
private CategoryService categoryService;
@GetMapping("/")
public ResponseEntity<List<Category>> findAll() {
List<Category> all = categoryService.getAll();
if (all.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(all, HttpStatus.OK);
}
@GetMapping("/{id}")
public ResponseEntity<Category> findById(@PathVariable int id) {
Category obj = categoryService.get(id);
if (obj == null) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(obj, HttpStatus.OK);
}
@PostMapping("/")
public ResponseEntity<Category> createMainSlider(@RequestBody Category obj) {
System.out.println("-------rest Post");
return new ResponseEntity<>(categoryService.add(obj), HttpStatus.CREATED);
}
@PutMapping("/{id}")
public ResponseEntity<Category> update(@RequestBody Category obj, @PathVariable int id) {
Category obj1 = categoryService.update(obj);
System.out.println(obj);
return new ResponseEntity<>(obj1, HttpStatus.OK);
}
@DeleteMapping("/{id}")
public ResponseEntity<Category> deleteEmp(@PathVariable int id) {
categoryService.delete(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
My Ajax code:
$('.deleteBtn').bind('click',function(e){
e.preventDefault();
$.ajax({
type:'DELETE',
url : "/rest/categories/"+$(e.currentTarget).data('id'),
xhrFields: {
withCredentials: true
},
success : function(result) {
location.reload();
console.log(result);
},
error : function(e) {
alert("Error!")
console.log("ERROR: ", e);
}
})
})
My ajax request header like this:
EDIT: the [GET]
requests are working correctly, but [PUT,POST,DELETE]
do not work.