【问题标题】:Trouble connecting angular frontEnd with javaBackend?无法将角度前端与 javaBackend 连接起来?
【发布时间】:2020-05-13 19:19:51
【问题描述】:

我正在尝试在后端调用 API,但我有一些错误,我不知道是什么原因造成的。 在我在后端配置 spring 安全性之后问题就开始了。 该调用应激活预检请求选项 在我的后端文件中,我有

@Configuration
@EnableWebSecurity
public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {    
            http.csrf().disable();
            http.authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                    .anyRequest().authenticated()
                    .and()
//            .formLogin().and()
                .httpBasic();
    }
}

在前端,我有这部分代码。

  executeHelloWorldServiceWithPathVariable(name) {
    const basicAuthHeaderString = this.createBasicAuthenticationHttpHeader();

    const headers = new HttpHeaders({
        Authorization: basicAuthHeaderString
      });
    return this.http.get<HelloWorldBean>(`http://localhost:8080/hello-world/path-variable/${name}`,
      {headers});
  }

  createBasicAuthenticationHttpHeader() {
    const username = 'start';
    const password = 'end';
    const basicAuthHeaderString = 'Basic ' + window.btoa(username + ':' + password);
    return basicAuthHeaderString;
  }

在后台,我已经包含了

@CrossOrigin(origins = "http://localhost:4200")

但是,我仍然无法调用此 API 在控制台中,我应该得到类似 OPTION 方法的东西,但实际上,我得到了这些:

一般

Request URL: http://localhost:8080/hello-world/path-variable/start
Referrer Policy: no-referrer-when-downgrade

响应头

Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: keep-alive
Content-Length: 0
Date: Tue, 28 Jan 2020 11:11:49 GMT
Expires: 0
Keep-Alive: timeout=60
Pragma: no-cache
WWW-Authenticate: Basic realm="Realm"
WWW-Authenticate: Basic realm="Realm"
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

请求头

接受:application/json、text/plain、/ 接受编码:gzip、deflate、br 接受语言:en,cs;q=0.9,en-US;q=0.8 授权:Basicc3RhcnQ6ZWVuZA== 连接:保持活动 主机:本地主机:8080 来源:http://localhost:4200 推荐人:http://localhost:4200/welcome/start Sec-Fetch-Mode: cors Sec-Fetch-Site:同一站点 用户代理:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36

在控制台中,我看到了这个错误

【问题讨论】:

    标签: java angular typescript cors


    【解决方案1】:

    尝试在您的安全配置中添加 cors 策略:

    @Configuration
    @EnableWebSecurity
    public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {    
                http.csrf().disable();
                http.cors();
                http.authorizeRequests()
                    .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                        .anyRequest().authenticated()
                        .and()
    //            .formLogin().and()
                    .httpBasic();
        }
    }
    

    【讨论】:

    • 好的,Cors 的主要错误已经消失,但现在我正在尝试调用任何其他建议的 API 有 401
    • 这很可能是因为您只允许OPTIONS 请求,所以其他所有请求都是未经授权的。它在这一行:http.authorizeRequests().antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
    • 我认为问题不存在,因为即使我将其更改为 Http.method.GET 仍然不起作用
    【解决方案2】:

    SpringSecurityConfigurationBasicAuth尝试添加这个方法

    @Bean
      CorsConfigurationSource corsConfigurationSource() {
          CorsConfiguration configuration = new CorsConfiguration();
          configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
          configuration.setAllowedMethods(Arrays.asList("GET","POST"));
          UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
          source.registerCorsConfiguration("/**", configuration);
          return source;
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-22
      • 2012-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多