SpringSecurity-2.7中跨域问题
访问测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button id="btn">发起异步请求</button>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
let btnEl = document.querySelector('#btn');
btnEl.onclick = function () {
console.log('click......................');
axios({
url: 'http://localhost:8080/login',
method: 'post',
data: {
username: 'zhangsan',
password: '123456',
},
}).then((res) => {
console.log(res);
});
};
</script>
</body>
</html>
- 请求测试
SpringSecurity-配置
config
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((authorizeHttpRequests) ->
authorizeHttpRequests
.antMatchers(HttpMethod.OPTIONS, "/login").permitAll()
.anyRequest().authenticated()
);
http.cors().configurationSource(corsConfigurationSource());
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowCredentials(true);
configuration.setAllowedMethods(Arrays.asList("*"));
configuration.setAllowedHeaders(Arrays.asList("*"));
configuration.setMaxAge(Duration.ofHours(1));
configuration.setAllowedOriginPatterns(Arrays.asList("*"));
source.registerCorsConfiguration("/**", configuration);
return source;
}