Spring security 受CORS策略阻止的SpringBoot

Spring security 受CORS策略阻止的SpringBoot,spring-security,spring-security-oauth2,Spring Security,Spring Security Oauth2,在使用前端源代码调用后端java服务器时,我遇到了以下错误 Access to XMLHttpRequest at 'http://localhost:8513/oauth/token' from origin 'http://localhost:9513' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP

在使用前端源代码调用后端java服务器时,我遇到了以下错误

Access to XMLHttpRequest at 'http://localhost:8513/oauth/token' from origin 'http://localhost:9513' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
我使用的是springboot(2.2.4.RELEASE)+OAuth2(2.2.1.RELEASE)+Jwt(1.0.9.RELEASE)。将我的pom.xml粘贴到这里


org.springframework.cloud

但是帮不了我。

我找到了原因。因为我在spring security中使用了Oauth+JWT。SpringSecurity使用筛选器设置cors,但SpringSecurity中很少有筛选器(@Order(Ordered.HIGHEST_priority))因此为我的过滤器设置一个序列很重要。附加的源代码供您参考

Cors配置

@配置
公共类GlobalCorsConfiguration{
@豆子
公共公司过滤器{
CorsConfiguration CorsConfiguration=新的CorsConfiguration();
corsConfiguration.setAllowCredentials(真);
corsConfiguration.addAllowedOrigin(“*”);
corsConfiguration.addAllowedHeader(“*”);
corsConfiguration.addAllowedMethod(“*”);
UrlBasedCorsConfigurationSource UrlBasedCorsConfigurationSource=新的UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration(“/**”,corsConfiguration);
返回新的CorsFilter(urlBasedCorsConfigurationSource);
}
}
身份验证配置

//此@Order对于在spring security中设置筛选器序列非常重要。
@顺序(有序。最高优先级)
@配置
@启用Web安全性
公共类WebSecurity配置器扩展WebSecurity配置器适配器{
@自动连线
用户服务用户服务;
@凌驾
@Bean(name=BeanIds.AUTHENTICATION\u管理器)
公共AuthenticationManager authenticationManagerBean()引发异常{
返回super.authenticationManagerBean();
}
@凌驾
@豆子
公共UserDetailsService userDetailsServiceBean()引发异常{
返回super.userDetailsServiceBean();
}
@凌驾
受保护的无效配置(AuthenticationManagerBuilder auth)引发异常{
auth.userDetailsService(userService).passwordEncoder(新的BCryptPasswordEncoder());
}
@凌驾
受保护的无效配置(HttpSecurity http)引发异常{
http
.requestMatchers().antMatchers(HttpMethod.OPTIONS,“/oauth/**”)
.及()
.csrf().disable().formLogin()
.及()
.cors();
}
}
资源配置

@配置
公共类ResourceServerConfiguration扩展了ResourceServerConfigurerAdapter{
@凌驾
public void configure(HttpSecurity http)引发异常{
http.authorizeRequests()
.及()
.authorizeRequests().antMatchers(HttpMethod.POST,“/v1/moikitos/user/”).permitAll()
.及()
.authorizeRequests().antMatchers(HttpMethod.POST,“/v1/moikeitos/**”).authorized();
}
}

此时,我使用nginx将端口9513中的前端应用程序和端口8513中的spring boot应用程序合并到某个端口下。但我需要允许csrf。如果你需要我的完整代码库,你可以在这里找到
@Configuration
@EnableAuthorizationServer
public class JWTOAuth2Config extends AuthorizationServerConfigurerAdapter{

    private static final int accessTokenValiditySeconds = 5 * 60 * 1;
    private static final int refreshTokenValiditySeconds = 60 * 60 * 1;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenEnhancer jwtTokenEnhancer;


    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;


    @Autowired
    private UserService userService;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtTokenEnhancer, jwtAccessTokenConverter));

        endpoints
        .tokenStore(tokenStore)
        .accessTokenConverter(jwtAccessTokenConverter)
        .tokenEnhancer(tokenEnhancerChain)
        .authenticationManager(authenticationManager)
        .userDetailsService(userService);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

      clients.inMemory()
              .withClient("organization")
              .secret(PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("organization666"))
              .authorizedGrantTypes("refresh_token", "password", "client_credentials")
              .scopes("webclient", "mobileclient")
              .accessTokenValiditySeconds(accessTokenValiditySeconds)
              .refreshTokenValiditySeconds(refreshTokenValiditySeconds);
  }
}
@Configuration
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure (HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers(HttpMethod.GET, "/v1/moikiitos/**")
        .authenticated()
        .and().cors()
        .and().csrf().disable();
    }
}
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter{

    @Autowired
    UserService userService;

    @Value("${security.enable-csrf}")
    private boolean csrfEnabled;


    @Override
    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    public AuthenticationManager authenticationManagerBean() throws Exception{
        return super.authenticationManagerBean();
    }

    @Override
    @Bean
    public UserDetailsService userDetailsServiceBean() throws Exception{
        return super.userDetailsServiceBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);

        if(!csrfEnabled) {
            http.cors().and()
            .csrf().disable();
        }
    }
}
security.enable-csrf=false