SpringSecurity 为什么局部刷新的url 会403
时间: 2024-02-28 15:25:27 浏览: 24
Spring Security 是基于 Servlet Filter 实现的安全框架,它默认会对所有请求进行安全检查,包括局部刷新的 AJAX 请求。如果 AJAX 请求的 URL 没有被授权,Spring Security 会返回 403 禁止访问的错误。
解决这个问题的方法有以下两种:
1.配置 Spring Security 忽略 AJAX 请求
在 Spring Security 的配置类中,可以添加以下代码:
```
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/**").permitAll()
.anyRequest().authenticated()
.and()
.csrf().disable()
.headers().frameOptions().disable();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
}
}
```
其中,`.antMatchers("/api/**").permitAll()` 表示忽略 `/api/` 开头的 AJAX 请求的安全检查。
2.在 AJAX 请求中添加 CSRF Token
如果不想忽略 AJAX 请求的安全检查,可以在 AJAX 请求中添加 CSRF Token,这样 Spring Security 就会认为该请求是安全的。具体方法是在页面中添加如下代码:
```
<meta name="_csrf" content="${_csrf.token}" />
<meta name="_csrf_header" content="${_csrf.headerName}" />
```
然后在 AJAX 请求的头部中添加以下代码:
```
headers: {
"${_csrf.headerName}": "${_csrf.token}"
}
```
这样就可以保证 AJAX 请求的安全性,并且不会返回 403 禁止访问的错误。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)