小编Muh*_*edH的帖子

Spring Security 的 AJAX 请求给出 403 Forbidden

我有一个基于spring boot、spring-security、thymeleaf的网站,在某些情况下我也使用ajax。

问题:我在 Spring Security 中使用表单登录安全性。在浏览器中,登录后我可以使用rest API (GET),但是使用Ajax,它会返回http 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("/");

}
Run Code Online (Sandbox Code Playgroud)

REST API 我测试正确:

@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 …
Run Code Online (Sandbox Code Playgroud)

java ajax spring spring-security spring-boot

5
推荐指数
1
解决办法
8589
查看次数

标签 统计

ajax ×1

java ×1

spring ×1

spring-boot ×1

spring-security ×1