Spring security 与spring boot安全性相关的CORS问题
我使用spring boot、spring security,希望避免任何cors操作。我在这里尝试第二个答案(),我需要向cors添加自定义筛选器,下面是筛选器:Spring security 与spring boot安全性相关的CORS问题,spring-security,cors,Spring Security,Cors,我使用spring boot、spring security,希望避免任何cors操作。我在这里尝试第二个答案(),我需要向cors添加自定义筛选器,下面是筛选器: @Component public class CorsFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(final HttpServletRequest request, final HttpServle
@Component
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, HEAD");
response.addHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
response.addHeader("Access-Control-Expose-Headers", "Access-Control-Allow-Origin, Access-Control-Allow-Credentials");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addIntHeader("Access-Control-Max-Age", 10);
filterChain.doFilter(request, response);
}
}
所以我在那里创建了类insert CorsFilter,我犯了一个错误:
'springSecurityFilterChain' threw exception; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'corsFilter' is expected to be of type 'org.springframework.web.filter.CorsFilter' but was actually of type 'fa.backend.core.security.CorsFilter'
我的安全配置如下所示:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().antMatcher("/users").authorizeRequests()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.and()
.addFilterBefore(
new JWTLoginFilter(tokenAuthentication, authenticationManagerBean()),
UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
你能告诉我怎么修吗?我的目标是禁用任何cors操作,因为我从前端收到:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8081' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
删除配置覆盖中http后的“cors()”和“and”部分。下面是代码片段
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/users").authorizeRequests()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.and()
.addFilterBefore(
new JWTLoginFilter(tokenAuthentication, authenticationManagerBean()),
UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}