【问题标题】:Access to XMLHttpRequest at '' () from origin '' has been blocked by CORS policy:No 'Access-Control-Allow-Origin' header is present从源 '' 访问 XMLHttpRequest 在 '' () 已被 CORS 策略阻止:不存在 'Access-Control-Allow-Origin' 标头
【发布时间】:2019-04-26 17:20:13
【问题描述】:

我在从 openid connect 注销时遇到以下问题。

"从源访问 '' 处的 XMLHttpRequest(从 '' 重定向) 'http://localhost:8080' 已被 CORS 策略阻止:否 请求中存在“Access-Control-Allow-Origin”标头 资源。”

网络通话显示“已取消”状态。

这里是代码 安全配置.java

@Override
    protected void configure(HttpSecurity http) throws Exception {
        LOG.info("in configure httpsecurity");
        http.csrf().disable().cors().and()
        .addFilterAfter(new OAuth2ClientContextFilter(), AbstractPreAuthenticatedProcessingFilter.class)
        .addFilterAfter(myFilter(), OAuth2ClientContextFilter.class)
        .httpBasic().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint(openIdConfig.getEntrypoint()))
        .and()
        .authorizeRequests()
        .antMatchers(openIdConfig.getEntrypoint()).permitAll()
        .anyRequest().authenticated()
        .and().logout()//.clearAuthentication(true)
        .logoutUrl(openIdConfig.getLogoffURL()+openIdConfig.getRedirectUri()).permitAll()
       .invalidateHttpSession(true)
          .deleteCookies(OpenIDConstants.SESSION_TOKEN, OpenIDConstants.USERNAME,
          OpenIDConstants.JSESSIONID)
          .logoutSuccessHandler(logoutSuccessHandler())
          .logoutSuccessUrl(openIdConfig.getRedirectUri());
        ;
        LOG.info("in configure httpsecurity end");
     // @formatter:on
    }

【问题讨论】:

  • 这是cross-origin相关的问题,你需要使用cors中间件在两个不同的服务器之间进行通信
  • 你能发布整个安全配置类吗?

标签: spring-boot angular6 spring-security-oauth2


【解决方案1】:

您可能确实在安全级别启用了 CORS,但没有在 Web 级别启用。 要在 Web 级别启用 CORS,您可以在方法级别、类级别或整个应用程序中执行此操作。

方法级别

@CrossOrigin(origins = "http://example.com")
@GetMapping(path="/")
public String homeInit(Model model) {
    return "home";
}

班级级别

@CrossOrigin(origins = "*", allowedHeaders = "*")
@Controller
public class HomeController
{
    @GetMapping(path="/")
    public String homeInit(Model model) {
        return "home";
    }
}

全球

@Configuration
@EnableWebMvc
public class CorsConfiguration extends WebMvcConfigurerAdapter
{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("GET", "POST");
    }
}

或者,对于 Spring Boot 应用程序,推荐的方式:

@Configuration
public class CorsConfiguration
{
    @Bean
    public WebMvcConfigurer corsConfigurer()
    {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}

【讨论】:

  • 在添加了上述所有配置后,我仍然面临这个问题。
  • @Saritha 你能把项目放到 Github 上吗?
猜你喜欢
  • 2021-06-30
  • 1970-01-01
  • 2021-04-03
  • 2022-09-27
  • 2021-03-27
  • 2020-04-15
  • 2019-08-09
  • 2019-08-10
  • 2020-01-30
相关资源
最近更新 更多