当前位置: 首页 > 知识库问答 >
问题:

在Spring Boot应用程序中全局禁用post请求后,CORS策略阻止了它[重复]

顾穆冉
2023-03-14
Access to XMLHttpRequest at 'http://localhost:8080/users/register' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
 register(username, firstName, lastName, email, password) {
    return this.http.post<any>(`http://localhost:8080/users/register`,
    {
      username,
      firstName,
      lastName,
      email,
      password
    });
  }
    @Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("*");
    }
}
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
    private UserDetailsService userDetailsService;
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public WebSecurity(@Qualifier("userDetailsServiceImpl") UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userDetailsService = userDetailsService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                .addFilter(new JWTAuthorizationFilter(authenticationManager()));
    }

    @Override
    public void configure(org.springframework.security.config.annotation.web.builders.WebSecurity web) {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }
}

我是一个乞丐,所以如果我错过了什么请告诉我。

共有1个答案

衡高寒
2023-03-14

这种飞行前请求(requestmethod.options)是由一些浏览器作为一种安全措施发出的,以确保服务器信任正在执行的请求。这意味着服务器理解在请求上发送的方法、源和头是安全的。用于CORS的WebConfig

您可以为CORS起源配置创建一个WebConfig类

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

    }

}
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // by default uses a Bean by the name of corsConfigurationSource
            .cors().and()
            ...
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
 类似资料:
  • 我了解了Firebase托管的标头配置,所以我这样做了: 在app中,在didChangeDependencies中有一个简单的firebase初始化,带有所需的数据。然后firebase auth . instance . signinwithemailandpassword(...)关于index.html的一段关于火垒的话: 我在Chrome中测试过很多次,总是失败。只有在localhost

  • 我有一个Android、Ios和web应用程序,它使用php作为后端。所有Api在android和ios中都运行良好,但在web中抛出CORS错误。得到这样的错误 访问位于“”的XMLHttpRequesthttps://example.com/api“起源”http://localhost:49168'已被CORS策略阻止:请求的资源上不存在'Access Control Allow Origi

  • 当我不接触任何关于CORS的东西时,浏览器会向我显示常见错误 CORS策略阻止了从源http://localhost:3000获取http://localhost:8080/denodo-testwebapp/tags的访问 但与此同时,在邮递员上做一个GET请愿书,我用所有数据来回复 但当我试图通过添加以下代码禁用CORS时: 我不再有浏览器错误,但现在,在postman上做同样的GET请愿书,

  • 访问位于“”的XMLHttpRequesthttp://localhost:8080/api/auth/signup“起源”https://mysuite.ru'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:飞行前请求不允许重定向。 通过nginx重定向 使现代化 请求标头: 加载项nginx: 还没有结果

  • ... 我在Java Spring Boot后端中使用了以下符号: 这是一个错误,我得到: