为什么在spring boot中向安全资源提交请求时出现cors错误?

laximzn5  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(241)

我已经使用jwt令牌在我的应用程序中实现了Spring Security ,我在Spring Security 中有以下配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(        
        prePostEnabled = true)  
public class MSSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    private AuthEntryPointJwt unauthorizedHandler;

    @Bean
    public AuthTokenFilter authenticationJwtTokenFilter() {
        return new AuthTokenFilter();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
         web.ignoring().antMatchers("/companies/UnAuth/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()           
            .authorizeRequests()
            .antMatchers("/companies/Auth/**").authenticated()
            .antMatchers("/companies/Auth/Update").authenticated()
            .antMatchers("/companies/Auth/Delete").authenticated();

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }

我在相关控制器上有以下cors注解:

@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
@RestController
@RequestMapping("/companies")
@Slf4j
public class CompanyController {

我试图在angular中将以下内容添加到http侦听器中:

authReq.headers.set("Access-Control-Allow-Origin", "http://localhost:4200");
    authReq.headers.set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

从angular 9应用程序提交请求时,我无法通过安全检查,并且我收到cors错误:

`Access to XMLHttpRequest at 'http://localhost:9001/companies/Auth/Update' 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 resourc`e.
ws51t4hk

ws51t4hk1#

请求不包含“access control allow origin”标题,您应该将其添加到标题中,它允许远程计算机访问您通过rest发送的内容。
如果要允许所有远程主机访问您的api内容,应按如下方式添加:

Access-Control-Allow-Origin: *

您还可以指定特定的主机:

Access-Control-Allow-Origin: http://example.com

您应该在pom.xml文件中修改依赖项并允许cors标头,从access control allow origin标头中选择appart您还需要向请求中添加一些内容,请在此处查找更多信息:
https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

相关问题