我的后端应用程序是Sping Boot ,前端应用程序是React。我尝试从React访问Spring Boot应用程序,但遇到此错误:
有一些Spring安全配置;
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
/**
* This method is permitting endpoints
* @author***
* */
@Override
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.cors()
.and()
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(handler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers("/auth/**", "/swagger-ui.html", "/swagger-ui/index.html", "/swagger-ui/**", "/v3/api-docs/**")
.permitAll()
.anyRequest().authenticated();
httpSecurity.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
并且存在JWT过滤器;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
String jwt = extractJwtFromRequest(request);
if (jwt != null && jwtTokenProvider.validateJwtToken(jwt)) {
String username = jwtTokenProvider.getUserIdFromJwtToken(jwt);
UserDetails userDetails = userDetailsServiceImp.loadUserByUsername(username);
if (userDetails != null) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
userDetails,
null,
userDetails.getAuthorities()
);
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
}
} catch (Exception e) {
e.printStackTrace();
}
filterChain.doFilter(request, response);
}
最后请求从网络选项卡中响应;
异常错误:当allowCredentials为true时,allowedOrigins不能包含特殊值“*”,因为该值不能在“Access-Control-Allow-Origin”响应标头上设置。要允许将凭据用于一组源,请显式列出它们或考虑改用“allowedOriginPatterns”。**
从后端服务器。
1条答案
按热度按时间b5buobof1#
你的问题是因为
与以下各项结合使用:
setAllowCredentials
表示响应将包含值为true
的Access-Control-Allow-Credentials标头,并发送给调用客户端。如果允许浏览器中的javascript访问凭据信息(如会话Cookie、授权标头或TLS客户端证书),则将设置此标头。实际上,您已经设置了允许ANY origin(因为您使用了通配符
*
)接触/使用返回的凭据信息。"这很不安全"
这就是警告告诉你的:
当allowCredentials为true时,allowedOrigins不能包含特殊值“*”,因为该值不能在“Access-Control-Allow-Origin”响应标头上设置。若要允许一组源的凭据,请显式列出它们或考虑改用“allowedOriginPatterns”。
您不能同时拥有
allowCredentials
到true
和allowedOrigins
到*
。如果您希望浏览器中的javascript能够接触凭据信息,则必须使用
allowedOriginPatterns
显式设置允许的来源。例如:
或者,您只需禁用所有允许凭据。