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

CORS策略阻止了对“来自origin”的“()”处XMLHttpRequest的访问:没有“Access-Control-Allow-Origin”标头

班泽语
2023-03-14
@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
    }

共有1个答案

黄宏大
2023-03-14

您可能在安全级别上启用了CORS,但在web级别上没有。要在web级别上启用CORS,您可以在方法级别、类级别或整个应用程序上启用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");
    }
}
@Configuration
public class CorsConfiguration
{
    @Bean
    public WebMvcConfigurer corsConfigurer()
    {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}
 类似资料: