SpringSecurity解决POST方式下CSRF问题

谁践踏了优雅 2023-07-25 05:30 5阅读 0赞

问题现象HTTP Status 403-Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

原因:Spring Security为防止CSRF(Cross-site requetst forgery跨站请求伪造)的发生,限制了除了get以外的大多数方法。

解决方案①(后端常用):
​ 屏蔽CSRF控制,即Spring Security不再限制CSRF,进行配置:

  1. @Override
  2. protected void configure(HttpSecurity http) throws Exception {
  3. //屏蔽CSRF控制
  4. http.csrf().disable()
  5. ...
  6. }

解决方案②:
定义headerspost方式提交的时候带上headers的信息:

  1. var headers = { };
  2. headers['X-CSRF-TOKEN'] = "[[${_csrf.token}]]";
  3. $.ajax({
  4. url: url,
  5. type: "POST",
  6. headers: headers,
  7. dataType: "json",
  8. success: function(result) {
  9. }
  10. });

解决方案③:
直接作为参数提交:

  1. $.ajax({
  2. url: url,
  3. data: {
  4. "[[${_csrf.parameterName}]]": "[[${_csrf.token}]]"
  5. },
  6. type: "POST",
  7. dataType: "json",
  8. success: function(result) {
  9. }
  10. });

解决方案④:
form表单提交的时候,作为隐藏参数提交

  1. <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}">

发表评论

表情:
评论列表 (有 0 条评论,5人围观)

还没有评论,来说两句吧...

相关阅读