java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.*;
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
/*
* Set these headers
* response.setHeader("Strict-Transport-Security", "max-age=31536000");
response.setHeader("X-XSS-Protection", "1; mode=block");
response.setHeader("X-Content-Type-Options", "nosniff");
response.setHeader("X-Frame-Options", "SAMEORIGIN");
*/
http.csrf().disable();
http.headers()
.defaultsDisabled()
.cacheControl()
.and()
.httpStrictTransportSecurity().maxAgeInSeconds(31536000).includeSubDomains(false)
.and()
.xssProtection().block(true)
.and()
.contentTypeOptions()
.and()
.frameOptions().sameOrigin()
.and()
.csrf().disable();
http.cors(cors -> cors.configurationSource(corsFilter()));
}
@Bean
public CorsConfigurationSource corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedOrigins(Collections.singletonList("http://localhost:3000")); // Allow specific origin
corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); // Allow HTTP methods
corsConfiguration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type", "X-Requested-With")); // Allow headers
corsConfiguration.setAllowCredentials(true); // Allow credentials (cookies, etc.)
source.registerCorsConfiguration("/**", corsConfiguration);
return source;
}
}
前后端分离项目,http://localhost:3000是前端地址