Moh*_*war 2 spring spring-mvc spring-security cors spring-boot
我正在使用Spring Boot版本2.0.2Release。下面是我的安全配置
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
prePostEnabled = true,
securedEnabled = true,
jsr250Enabled = true)
@ComponentScan("com.mk")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationProvider myAuthenticationProvider;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.cors().configurationSource(corsConfigurationSource())
.and()
.csrf().disable()
.anonymous().and()
.authorizeRequests()
.antMatchers(HttpMethod.GET,"/index.html").permitAll()
.antMatchers(HttpMethod.POST,"/login").permitAll()
.antMatchers(HttpMethod.GET,"*").authenticated()
.and().httpBasic();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
Run Code Online (Sandbox Code Playgroud)
由于CORS的问题,我无法调用任何API(包括login是allowAll)。
在浏览器上,我得到了(它与Postman一起使用,因为在那里没有进行CORS检查)
无法加载http:// localhost:8080 / myurl:对预检请求的响应未通过访问控制检查:所请求的资源上没有'Access-Control-Allow-Origin'标头。因此,不允许访问源' http:// localhost:4200 '。响应的HTTP状态码为403。
从 Spring 查看本指南:
https://spring.io/guides/gs/rest-service-cors/
在 Spring Boot 中添加 CORS 支持的方法很少。
使用全局配置:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
}
};
}
Run Code Online (Sandbox Code Playgroud)
并使用@CrossOrigin注释:
@CrossOrigin(origins = "http://localhost:9000")
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
Run Code Online (Sandbox Code Playgroud)
无需添加任何额外的Filters或WebMvcConfigurer。主要问题是'Access-Control-Allow-Origin'没有出现在标头中,因为corsConfigurationSource没有添加必要的配置来获取相关的 CORS 响应标头。因此,我们配置时必须添加以下缺少的配置CorsConfigurationSource
configuration.addAllowedOrigin("*");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
Run Code Online (Sandbox Code Playgroud)
我们必须CorsConfigurationSource 如下配置 cors
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.cors().configurationSource(corsConfigurationSource())
.and()
.....
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
configuration.setAllowCredentials(true);
//the below three lines will add the relevant CORS response headers
configuration.addAllowedOrigin("*");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
Run Code Online (Sandbox Code Playgroud)
如果有人CORS在使用以下组合时遇到 Spring Boot 2.4.0 及更高版本的问题,请参考答案
CorsConfigurationSource#setAllowedOrigins价值为*
和
CorsConfigurationSource#setAllowCredentials价值为true
尽管Spring安全性提供了一种在http configurer中配置CORS的方法,但是有一种更加干净的方法可以将CORS过滤器添加到应用程序中,
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyCORSFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
}
Run Code Online (Sandbox Code Playgroud)
对过滤器进行最高优先级排序可确保MyCORSFilter实现javax.servlet.Filter是链中的第一个实现。希望这可以帮助
| 归档时间: |
|
| 查看次数: |
10077 次 |
| 最近记录: |