gpt4 book ai didi

spring - CORS Spring 安全过滤器与 WebMvcConfigurer.addCorsMappings

转载 作者:行者123 更新时间:2023-12-01 21:23:44 25 4
gpt4 key购买 nike

WebSecurityConfigurerAdapter类的configure方法中的cors()过滤器和WebMvcConfigurer的创建bean有什么区别并覆盖 addCorsMappings 方法?我们什么时候使用哪个?谁能解释一下?

@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000");
}
};
}

对比

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()
.csrf().disable()
.authorizeRequests()
.mvcMatchers("/rest/**").authenticated()
.anyRequest().permitAll()
.and()
.oauth2ResourceServer().jwt().jwtAuthenticationConverter(this.jwtAuthenticationConverter())
;
}

最佳答案

Spring Web MVC

WebMvcConfigurerSpring Web MVC 的一部分图书馆。使用 addCorsMappings 配置 CORS 将 CORS 添加到由 Spring Web MVC 处理的所有 URL,请参阅 1.7.2. Processing :

Spring MVC HandlerMapping implementations provide built-in support for CORS. After successfully mapping a request to a handler, HandlerMapping implementations check the CORS configuration for the given request and handler and take further actions.

如果未使用 Spring Security(非安全应用程序)或并非所有 Spring Web MVC URL 都由 Spring Security 处理(某些 ULR 是不安全的),则必须使用它。

您不能将它用于非 Spring Web MVC URL,例如 JSF、Servlet、JAX-WS、JAX-RS...

Spring 安全

WebSecurityConfigurerAdapter Spring Security 的一部分图书馆。使用 cors() 配置 CORS将 CORS 添加到由 Spring Security 处理的所有 URL,请参阅 15.8. CORS :

Spring Framework provides first class support for CORS. CORS must be processed before Spring Security because the pre-flight request will not contain any cookies (i.e. the JSESSIONID). If the request does not contain any cookies and Spring Security is first, the request will determine the user is not authenticated (since there are no cookies in the request) and reject it.

The easiest way to ensure that CORS is handled first is to use the CorsFilter.

如果你使用 Spring Security,你必须使用它。

如果您同时使用 Spring Web MVC 和 Spring Security,则可以共享配置,请参阅 15.8. CORS :

If you are using Spring MVC’s CORS support, you can omit specifying the CorsConfigurationSource and Spring Security will leverage the CORS configuration provided to Spring MVC.

关于spring - CORS Spring 安全过滤器与 WebMvcConfigurer.addCorsMappings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63426010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com