我有一个基于Spring boot、spring-security、thymeleaf的网站,在某些情况下我也使用ajax。
问题:
我在Spring Security中使用表单登录安全性。在浏览器中,登录后我可以使用restAPI(GET),但是使用ajax它会返回403,即使我的ajax请求在cookie中包含会话ID。
安全配置:
@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("/");
}
RestAPI我测试正确。
@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);
}
}
-我的ajax代码:
$('.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);
}
})
})
编辑[GET]请求正在正常工作,例如放置[PUT, POST,DELETE]不工作。
为什么. csrf().disable().cors()
有效?
CSRF代表跨站请求伪造
简而言之,它是一种令牌,与请求一起发送以防止攻击。为了使用Spring SecurityCSRF保护,我们首先需要确保我们对任何修改状态的东西使用正确的HTTP方法(PATCH
、POST
、PUT
和DELETE
-而不是GET
)。
一些框架通过禁用用户的会话来处理无效的CSRF令牌,但这会导致其自身的问题。相反,默认情况下,Spring Security的CSRF保护将产生HTTP403访问被拒绝。
Ajax和JSON请求
如果您使用JSON,则无法在HTTP参数中提交CSRF令牌。相反,您可以在HTTP标头中提交令牌。典型的模式是在元标记中包含CSRF令牌
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
//jQuery
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
谢谢大家
我通过禁用CSRF解决了它,我添加了这个
. csr f().disable().cor s()
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("/")
.and()
.csrf().disable().cors();
====== 编辑:
@帕特尔回答了一个有用的解释…多亏了他