springboot security跨域怎么处理 例如前端使用端口为8080 请求后端使用的端口8088
时间: 2023-07-15 15:15:51 浏览: 66
在Spring Security中,可以通过配置CorsFilter来处理跨域请求。具体做法如下:
1. 在Spring Boot项目中添加依赖
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
2. 创建CorsFilter配置类
```java
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
};
}
}
```
3. 配置Spring Security
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll()
.and()
.httpBasic();
}
}
```
以上代码中,我们使用了`WebMvcConfigurerAdapter`来配置CorsFilter,允许所有来源的请求,并指定允许的HTTP方法、请求头和Credentials。在Spring Security中,我们使用`http.cors()`来启用CorsFilter,同时禁用了CSRF防护。
需要注意的是,由于跨域请求中会先发送OPTIONS请求,因此我们需要在Spring Security中允许OPTIONS请求。上述示例中,我们使用`antMatchers(HttpMethod.OPTIONS).permitAll()`来允许所有的OPTIONS请求。