我们添加Spring Security到现有项目中.
从这一刻起,我们No 'Access-Control-Allow-Origin' header is present on the requested resource从服务器收到401 错误.
那是因为没有Access-Control-Allow-Origin标题附加到响应.为了解决这个问题,我们Filter在注销过滤器之前添加了我们自己的过滤器,但过滤器不适用于我们的请求.
我们的错误:
XMLHttpRequest无法加载
http://localhost:8080/getKunden.请求的资源上不存在"Access-Control-Allow-Origin"标头.http://localhost:3000因此不允许原点访问.响应具有HTTP状态代码401.
我们的安全配置:
@EnableWebSecurity
@Configuration
@ComponentScan("com.company.praktikant")
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private MyFilter filter;
@Override
public void configure(HttpSecurity http) throws Exception {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
source.registerCorsConfiguration("/**", config);
http.addFilterBefore(new MyFilter(), LogoutFilter.class).authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/*").permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws …Run Code Online (Sandbox Code Playgroud) 我有一个AbstractAuthenticationProcessingFilter我用来处理路径上的POST请求/sign-in.CORS预检请求返回404,因为没有匹配的路径.这对我来说很有意义.
我想知道的是,如果有一种方法可以通知Spring有一个过滤器处理POST(而不是一个控制器),那么Spring可以像控制器处理POST一样调度OPTIONS .用一个控制器写一个控制器是不好的做法PostMapping?我不确定这样做会怎么样,因为技术上过滤器处理POST.
谢谢你的帮助!
更新
这是我的设置.我最初是从手机发布的,因此无法添加这些详细信息.见下文.重申一下,没有控制器/sign-in.POST由JwtSignInFilter.处理.
CORS配置
@EnableWebMvc
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*") // TODO: Lock this down before deploying
.allowedHeaders("*")
.allowedMethods(HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.DELETE.name())
.allowCredentials(true);
}
}
Run Code Online (Sandbox Code Playgroud)
安全配置
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public JwtSignInFilter signInFilter() throws Exception {
return new JwtSignInFilter(
new AntPathRequestMatcher("/sign-in", HttpMethod.POST.name()),
authenticationManager()
);
}
@Bean
public JwtAuthenticationFilter authFilter() {
return new JwtAuthenticationFilter(); …Run Code Online (Sandbox Code Playgroud)