Настроить Spring для CORS

Я думаю, что все дали решение, я хотел бы объяснить причину неожиданного результата.

Прежде всего, здесь вы можете проверить происхождение и как оцениваются операторы (слева, справа, ассоциативный и т. д.).

http://php.net/manual/fa/language.operators.precedence.php

Теперь, если мы проанализируем ваши предложение.

$ paperType = 'bond';
$ description = 'Paper:'. ($ paperType == 'bond')? 'Bond': 'Other';

1) Мы рассмотрим таблицу и выясним, что скобки сначала оцениваются, а затем. (конкатенация), а в конце - тернарный оператор '?', поэтому мы могли бы связать это следующим образом:

// evaluate the parenthesis ... ($ paperType == 'bond')
$ description = ('Paper:'. 1)? 'Bond': 'Other';
//result
$ description = 'Paper: 1'? 'Bond': 'Other';

2) Теперь мы имеем тернарный оператор, мы знаем, что строка оценивается «true»

// php documentation При преобразовании в логическое значение следующие значения считаются FALSE:

... пустая строка и строка «0»

$ description = true? 'Bond': 'Other';

3) Наконец

$ description = 'bond';

Надеюсь, что я уточнил этот вопрос. Привет.

9
задан Milad 26 January 2019 в 12:59
поделиться

4 ответа

Ваш разрешенный источник - 127.0.0.1, но у вашей клиентской стороны есть ip 123.123.123.123. Попробуйте изменить это:

config.addAllowedOrigin("127.0.0.1");

На это:

config.addAllowedOrigin("123.123.123.123");
0
ответ дан Roddy of the Frozen Peas 26 January 2019 в 12:59
поделиться

Вы должны указать Spring Security использовать созданную вами конфигурацию CORS.

В моем проекте я настроил Spring Security следующим образом:

@Override
protected void configure(HttpSecurity http) throws Exception
{
    http
        .authorizeRequests()
        .antMatchers("/rest/protected/**")
        .authenticated()
     //Other spring sec configruation and then:
    .and()
        .cors()
        .configurationSource(corsConfigurationSource())

}

Где corsConfigurationSource():

@Bean
    CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        boolean abilitaCors = new Boolean(env.getProperty("templating.oauth.enable.cors"));
        if( abilitaCors )
        {
            if( logger.isWarnEnabled() )
            {
                logger.warn("CORS ABILITATI! Si assume ambiente di sviluppo");
            }
            CorsConfiguration configuration = new CorsConfiguration();
            configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200","http://localhost:8080", "http://localhost:8180"));
            configuration.setAllowedMethods(Arrays.asList(  RequestMethod.GET.name(),
                    RequestMethod.POST.name(), 
                    RequestMethod.OPTIONS.name(), 
                    RequestMethod.DELETE.name(),
                    RequestMethod.PUT.name()));
            configuration.setExposedHeaders(Arrays.asList("x-auth-token", "x-requested-with", "x-xsrf-token"));
            configuration.setAllowedHeaders(Arrays.asList("X-Auth-Token","x-auth-token", "x-requested-with", "x-xsrf-token"));
            source.registerCorsConfiguration("/**", configuration);
        }
        return source;
    }

Я надеюсь, что это полезно

Анджело

0
ответ дан Angelo Immediata 26 January 2019 в 12:59
поделиться

Это мой рабочий класс @Configuration для обработки запросов CORS, используемых только в среде разработки.

@Configuration
//@Profile(PROFILE_DEV)
  public class CorsConfiguration {

  @Bean
  public WebMvcConfigurer corsConfigurer() {
      return new WebMvcConfigurer() {
          @Override
          public void addCorsMappings(CorsRegistry registry) {
              registry.addMapping("/**")
                  .allowedOrigins("*")
                  .allowedHeaders("*")
                  .allowedMethods("*");
          }
      };
  }
}

Вы также должны настроить Spring Security на игнорирование HttpMethod.OPTIONS, используемого запросом предполетной проверки (в качестве исключения, которое вы упомянули)

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  //...
    @Override
    public void configure(WebSecurity web) throws Exception {
      web.ignoring()
            //others if you need
            .antMatchers(HttpMethod.OPTIONS, "/**");

    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
            .disable()
            .exceptionHandling()
            .and()
            .headers()
            .frameOptions()
            .disable()
            .and()
            .authorizeRequests()
            .antMatchers("/api/register").permitAll()
            .antMatchers("/api/activate").permitAll()
            .antMatchers("/api/authenticate").permitAll()
            .antMatchers("/api/**").authenticated();
    }

}

Потому что, когда вы используете cors, у вас есть Simple Request и Предварительно выданный запрос , который запускает HttpMethod.OPTIONS

0
ответ дан ValerioMC 26 January 2019 в 12:59
поделиться

Вам необходимо добавить @CrossOrigin уровень класса в вашем классе контроллера, как показано ниже

@CrossOrigin
public class SampleController {
    // Your code goes here
}

, к вашему классу контроллера покоя

0
ответ дан Sasikumar Murugesan 26 January 2019 в 12:59
поделиться
Другие вопросы по тегам:

Похожие вопросы: