java后端web服务有很多种方法可以实现跨域访问,配置很简单,今天这里我们用SpringSecurity的方式配置跨域访问,配置方法如下:
package com.wisea.config;
import org.springframework.context.annotation.Bean;
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.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
看网上的配置里会有代码如下:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
...
}
实际上并不起什么作用,总结,当工程中开启了@EnableWebSecurity的时候,我们只需要让spring容器中存在一个CorsFilter的跨域过滤器即可。 some days 几天发现问题: 当请求的中有redirect时,上面这段代码就必须了。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/188515.html原文链接:https://javaforall.cn