【问题标题】:SpringBoot blocked by CORS policySpringBoot 被 CORS 策略阻止
【发布时间】:2020-09-12 05:00:58
【问题描述】:

当我使用前端源代码调用我的后端 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

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
            <version>${oauth2.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-jwt</artifactId>
            <version>${spring-jwt.version}</version>
        </dependency>

我已经添加了允许 CORS 警察的配置,但它似乎根本不起作用。 我的安全配置在这里

JWTOAuth2Config.java

@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);
  }
}

ResourceServerConfiguration.java 在 ResourceServerConfigurerAdapter 的 HttpSecurity 类中配置允许 CORS,但不起作用。

@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();
    }
}

config 允许在 WebSecurityConfigurerAdapter 中的类 HttpSecurity 中使用 CORS,但也不起作用。 WebSecurityConfigurer.java

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();
        }
    }
}

将 csrf 设置为闪入 应用程序.properties

security.enable-csrf=false

即使我也为 WebMvcConfiguer 使用下面的 java 代码配置,但它也不起作用。

@Configuration
public class WebMvcConfig implements WebMvcConfigurer{

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
        .allowedOrigins("http://localhost:9513")
        .allowedMethods("*")
        .allowedHeaders("*");
    }
}

更重要的是,我还在我的控制器上使用了这个@CrossOrigin。 有人可以帮助我。欣赏。 我看过一些文章,例如origin has been blocked by CORS policy Spring boot and React 但不能帮助我。

【问题讨论】:

  • 此时,我使用nginx将我的9513端口的前端应用和8513端口的spring boot应用组合在了某个端口下。但我需要允许csrf。如果你需要我的完整代码库,你可以在这里找到github.com/ChenLin12138/Moikiitos

标签: spring-security spring-security-oauth2


【解决方案1】:

我找到了原因。因为我在 Spring Security 中使用了 Oauth + JWT。 Spring Security 使用过滤器来设置 Cors,但 Spring Security 中的过滤器很少。 (@Order(Ordered.HIGHEST_PRECEDENCE)) 所以为我的过滤器设置一个序列很重要。附上源代码供您参考。

Cors 配置

@Configuration
public class GlobalCorsConfiguration {

     @Bean
        public CorsFilter corsFilter() {
            CorsConfiguration corsConfiguration = new CorsConfiguration();
            corsConfiguration.setAllowCredentials(true);
            corsConfiguration.addAllowedOrigin("*");
            corsConfiguration.addAllowedHeader("*");
            corsConfiguration.addAllowedMethod("*");
            UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
            urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
            return new CorsFilter(urlBasedCorsConfigurationSource);
        }
}

身份验证配置

//This @Order is very important to setup the sequence of filter in spring security.
@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter{

    @Autowired
    UserService userService;

    @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 {
        http
        .requestMatchers().antMatchers(HttpMethod.OPTIONS, "/oauth/**")
        .and()
        .csrf().disable().formLogin()
        .and()
        .cors();
    }
}

资源配置

@Configuration
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure (HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers(HttpMethod.GET, "/v1/moikiitos/**").authenticated()
        .and()
        .authorizeRequests().antMatchers(HttpMethod.POST,"/v1/moikiitos/user/").permitAll()
        .and()
        .authorizeRequests().antMatchers(HttpMethod.POST,"/v1/moikiitos/**").authenticated();       
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-11
    • 2021-04-16
    • 2018-02-26
    • 2019-11-19
    • 2022-01-14
    • 2021-01-07
    • 2019-06-26
    • 2021-02-07
    相关资源
    最近更新 更多