【发布时间】:2015-10-28 17:05:27
【问题描述】:
我已经构建了一个 RestController,它应该可以帮助管理 Web 应用程序中的标签。我将通过 AJAX(使用 JQuery)调用所有方法,但 Spring-Boot 的默认安全性会导致以下结果(从 Postman 调用时):
{ “时间戳”:1438800538949, “状态”:403, “错误”:“禁止”, "message": "在请求参数 '_csrf' 或标头 'X-CSRF-TOKEN' 上发现无效的 CSRF Token 'null'。", “路径”:“/标签/添加” }
获取 CSRF 令牌以执行 JQuery 调用的最佳方法是什么?我认为这比禁用它更好。在 PostMan 中使用时会怎样?
这是控制器的代码:
@RestController
public class TagController {
@Autowired
private TagService tagService;
@RequestMapping(name = "/tag/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<TagList> getTagList() {
TagList result = new TagList(tagService.list());
return new ResponseEntity<TagList>(result, HttpStatus.OK);
}
@RequestMapping(name = "/tag/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> addTag(@RequestBody AlterTagForm form) {
try {
tagService.addTag(form.getArticleId(), form.getTagName());
return new ResponseEntity<>(HttpStatus.ACCEPTED);
} catch (EntityNotFoundException ex) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@RequestMapping(name = "/tag/remove", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> removeTag(@RequestBody AlterTagForm form) {
try {
tagService.removeTag(form.getArticleId(), form.getTagName());
return new ResponseEntity<>(HttpStatus.ACCEPTED);
} catch (EntityNotFoundException ex) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}
【问题讨论】:
-
因为是Rest api,所以可以在配置中禁用csrf check。通常这是由
httpSecurity.csrf().disable()在WebSecurityConfigurerAdapter .configure()方法中完成的。也可以通过httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)使其无状态。由于我没有看 Spring boot,不知道它是如何完成的。
标签: jquery spring spring-mvc spring-boot csrf