Ser*_*ich 4 spring-security cors
我使用弹簧靴、弹簧安全性并希望避免任何 cors 操作。我从这里尝试第二个答案(你能在 Spring 中完全禁用 CORS 支持吗?),我需要向 cors 添加自定义过滤器,这里是过滤器:
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
所以我在那里创建了类插入 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'
Run Code Online (Sandbox Code Playgroud)
我的安全配置如下所示:
@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);
}
Run Code Online (Sandbox Code Playgroud)
你能告诉我怎么修吗?我的目标是禁用任何 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.
Run Code Online (Sandbox Code Playgroud)
在配置覆盖中删除 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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3622 次 |
| 最近记录: |