【问题标题】:Angular spirngboot-preflight角弹簧引导预检
【发布时间】:2019-07-12 22:29:23
【问题描述】:

1.在 Spring boot 中,我在 pom.xml 文件中添加 "spring-boot-starter-security" 依赖项,并在角度控制台中出现错误提示 preflight error,即使我覆盖了该方法

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

    }
}
  1. 从浏览器我可以直接访问我的数据,方法是使用链接http://localhost:8080/users/.. 并提供我在 application.properties 文件中设置的用户 ID 和密码。

  2. 但通过使用相同的用户 ID 和密码,我无法获取数据的表单 restlet-client(用于测试 API 的类似 Postman 应用程序)。

proxy.conf.js 文件

module.exports = { "/myapi": { "target": "localhost:8080", "secure": false, "changeOrigin": true, "pathRewrite": { "^/myapi": "" } }

HttpInterceptorBasicAuthService.ts

@Injectable({ providedIn: 'root' }) export class HttpInterceptorBasicAuthService implements HttpInterceptor { constructor() { } intercept(request: HttpRequest<any>, next: HttpHandler){ let username='MSD' let password ='dummy' let basicAuthHeaderString = 'Basic '+ username + ':' + password; request=request.clone({ setHeaders : { Authorization : basicAuthHeaderString } }) return next.handle(request); } } 

任何人都知道为什么会发生此错误,请解决。

【问题讨论】:

  • 你好 Moni Shankar,在 WebConfig 类下面添加,然后再试一次,让我知道结果
  • 嗨兄弟@PatelRomil感谢您的解决方案...我的问题得到了解决,它与角度相关的proxy.conf.js文件
  • @PatelRomil 但兄弟如果添加提供者:[{提供:HTTP_INTERCEPTORS,useClass:HttpInterceptorBasicAuthService,multi:true}然后出现CROS错误......如果你有任何想法......请分享
  • 如果出现 CORS 问题,您必须在 Spring Boot 时添加一个 webconfig 类,请分享代理配置和 HttpInterceptorBasicAuthService 以获取更多详细信息
  • proxy.conf.js 文件---------- module.exports = { "/myapi": { "target": "localhost:8080", "secure": false , "changeOrigin": true, "pathRewrite": { "^/myapi": "" } }

标签: spring-boot cors angular7


【解决方案1】:

什么是预飞行?

此飞行前请求 (RequestMethod.OPTIONS) 由某些浏览器发出,作为一种安全措施,以确保正在完成的请求受到服务器的信任。这意味着服务器知道在请求上发送的方法、来源和标头是安全的。


选项 1:CORS 的 WebConfig

您可以为 CORS 源配置创建一个 WebConfig 类,这样我们不需要在每个控制器上都写@CrossOrigin

WebConfig.java

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class WebConfig implements Filter,WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
      HttpServletResponse response = (HttpServletResponse) res;
      HttpServletRequest request = (HttpServletRequest) req;
      System.out.println("WebConfig; "+request.getRequestURI());
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
      response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,observe");
      response.setHeader("Access-Control-Max-Age", "3600");
      response.setHeader("Access-Control-Allow-Credentials", "true");
      response.setHeader("Access-Control-Expose-Headers", "Authorization");
      response.addHeader("Access-Control-Expose-Headers", "USERID");
      response.addHeader("Access-Control-Expose-Headers", "ROLE");
      response.addHeader("Access-Control-Expose-Headers", "responseType");
      response.addHeader("Access-Control-Expose-Headers", "observe");
      System.out.println("Request Method: "+request.getMethod());
      if (!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
          try {
              chain.doFilter(req, res);
          } catch(Exception e) {
              e.printStackTrace();
          }
      } else {
          System.out.println("Pre-flight");
          response.setHeader("Access-Control-Allow-Origin", "*");
          response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT");
          response.setHeader("Access-Control-Max-Age", "3600");
          response.setHeader("Access-Control-Allow-Headers", "Access-Control-Expose-Headers"+"Authorization, content-type," +
          "USERID"+"ROLE"+
                  "access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with,responseType,observe");
          response.setStatus(HttpServletResponse.SC_OK);
      }

    }

}

选项 2 application.properties

# ENDPOINTS CORS CONFIGURATION (CorsEndpointProperties)
management.endpoints.web.cors.allow-credentials= # Whether credentials are supported. When not set, credentials are not supported.
management.endpoints.web.cors.allowed-headers= # Comma-separated list of headers to allow in a request. '*' allows all headers.
management.endpoints.web.cors.allowed-methods= # Comma-separated list of methods to allow. '*' allows all methods. When not set, defaults to GET.
management.endpoints.web.cors.allowed-origins= # Comma-separated list of origins to allow. '*' allows all origins. When not set, CORS support is disabled.
management.endpoints.web.cors.exposed-headers= # Comma-separated list of headers to include in a response.
management.endpoints.web.cors.max-age=1800s # How long the response from a pre-flight request can be cached by clients. If a duration suffix is not specified, seconds will be used.

选项 3 @CrossOrigin:

@CrossOrigin(origins = {"http://domain1.com"})

【讨论】:

    猜你喜欢
    • 2015-11-27
    • 2020-03-23
    • 1970-01-01
    • 2022-01-02
    • 2018-06-12
    • 2023-03-29
    • 1970-01-01
    • 2018-08-09
    • 2019-05-17
    相关资源
    最近更新 更多