HTTPS-запросы Spring Security и Angular 6 - PullRequest
0 голосов
/ 18 марта 2019

мое приложение backend в весенней загрузке и защищено с помощью sslЯ использовал OAuth2 для входа в Facebook.Также приложение внешнего интерфейса в Angular 7 и защищено ssl.Моя проблема - отправка запросов Angular в мое загрузочное приложение Spring.Все приложения это https.

PS Все работает, если я добавлю URL в webSecurity.ignoring ().и не защищать мой бэкэнд.Я думаю, что некоторые проблемы с безопасностью и HTTPS-запросами.СПАСИБО ЗА ПОМОЩЬ.

BACKEND

SecurityConfig.java

@RestController
@CrossOrigin(origins = "https://192.168.1.106:4400")
@Configuration
@Order(1000)
@EnableWebSecurity

public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserRepo userRepo;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .cors().and()
            .csrf().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.GET, "/unauth/**").permitAll()
            .antMatchers(HttpMethod.POST, "/unauth/upload").permitAll()

            .antMatchers(HttpMethod.POST, "/api/**").authenticated()
            .antMatchers(HttpMethod.PUT, "/api/**").authenticated()
            .antMatchers(HttpMethod.DELETE, "/api/**").authenticated()
            .antMatchers(HttpMethod.GET, "/api/**").authenticated()
            .anyRequest().permitAll()
            .and().logout().logoutSuccessUrl("/").permitAll();

}

@Override
public void configure(WebSecurity webSecurity) {
    webSecurity.ignoring().antMatchers(HttpMethod.GET, "/unauth/**");
    webSecurity.ignoring().antMatchers(HttpMethod.POST, "/unauth/**");
}
  webSecurity.ignoring().antMatchers(HttpMethod.POST, "/unauth/**");
}

SomeRestController.java

 @RestController
 @CrossOrigin(origins = "https://192.168.1.106:4400")
  @RequestMapping ("/api")
 public class ProductService {



@Autowired
private ProductRepo productRepo;

@CrossOrigin(origins = "https://192.168.1.106:4400")
@GetMapping("/products")
public List<Product> getProducts(){
    return productRepo.findAll();

}

SpringBootApplication.java

@SpringBootApplication
@EnableOAuth2Sso
@CrossOrigin(origins = {"https://192.168.1.106:4400"}, allowCredentials = "false")
public class MongoTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(MongoTestApplication.class, args);
    }
}

FRONTEND

SomeComponent.html

SomeComponent.ts

val:any = {};
  makeRequest(){
    this.http.get("https://localhost:8443/api/products").subscribe(value =>  {this.val = value; console.log(this.val.key)});
  }

ОШИБКА ошибка в браузере

Access to XMLHttpRequest at 'https://localhost:8443/api/brands' from origin 'https://192.168.1.106:4400' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
core.js.pre-build-optimizer.js:15714 ERROR n {headers: t, status: 0, statusText: "Unknown Error", url: "https://localhost:8443/api/brands", ok: false, …}

1 Ответ

0 голосов
/ 18 марта 2019

Отредактируйте ваш основной класс, как показано ниже, и удалите все @CrossOrigin из контроллеров.

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication
@EnableOAuth2Sso
public class MongoTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(MongoTestApplication.class, args);
    }

 @SuppressWarnings("deprecation")
    @Bean
        public WebMvcConfigurer corsConfigurer()
        {
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**").allowedMethods("GET", "PUT", "POST", "DELETE", "OPTIONS");
                }    
            };
        }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...