【发布时间】:2022-01-19 04:18:08
【问题描述】:
我有一个使用 Spring Security 和 Cors 过滤器的 Spring Boot 应用程序。有一个CorsFilter 如下,我尝试提出一个跨源请求
Axios.get("http://10.0.120.11:30500/user", { withCredentials: true })
.then((data) => console.log(data));
来自托管在 http://localhost:8080 的页面。但是,浏览器给出了 401。奇怪的是浏览器没有发送任何预检 (OPTIONS) 请求。
@Configuration
@EnableWebMvc
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
List<String> list = new ArrayList<>();
list.add("*");
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedHeaders(list);
corsConfiguration.setAllowedMethods(list);
corsConfiguration.setAllowedOriginPatterns(Arrays.asList("http://localhost:8080"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf()
.disable()
.formLogin()
.disable()
.httpBasic()
.disable()
.exceptionHandling()
.authenticationEntryPoint(new LoginAuthenticationEntryPoint())
//.authenticationEntryPoint(new RestAuthenticationEntryPoint())
.and()
.authorizeRequests()
.antMatchers("/",
"/error",
"/favicon.ico",
"/**/*.png",
"/**/*.gif",
"/**/*.svg",
"/**/*.jpg",
"/**/*.html",
"/**/*.css",
"/**/*.js")
.permitAll()
.antMatchers("/login/**","/auth/**", "/oauth2/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.oauth2Login()
.clientRegistrationRepository(getClientRegistrationRepository())
.authorizationEndpoint()
.authorizationRequestResolver(new CustomAuthorizationRequestResolver(getClientRegistrationRepository(),"/oauth2/authorize"))
.baseUri("/oauth2/authorize")
.authorizationRequestRepository(cookieAuthorizationRequestRepository())
.and()
.redirectionEndpoint()
.baseUri("/oauth2/callback/*")
.and()
.tokenEndpoint()
.accessTokenResponseClient(new CustomTokenResponseClient())
.and()
.userInfoEndpoint()
.userService(customOAuth2UserService)
.and()
.successHandler(oAuth2AuthenticationSuccessHandler)
.failureHandler(oAuth2AuthenticationFailureHandler);
// Add our custom Token based authentication filter
http.addFilterBefore(cookieAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
【问题讨论】:
标签: spring-boot spring-security cors preflight