角spirngboot-preflight

时间:2019-07-12 08:01:47

标签: spring-boot cors angular7

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

>
@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. 但是通过使用相同的用户名和密码,我无法获取数据的表单restlet-client(类似于Postman的类似应用程序,用于测试API)。

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

任何人都知道为什么会发生此错误,请进行清理。

1 个答案:

答案 0 :(得分:0)

什么是飞行前?

此预检请求(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"})