【问题标题】:No 'access-control-allow-origin' header is present on the requested resource With Resource Server in Spring Boot在 Spring Boot 中使用资源服务器请求的资源上不存在“access-control-allow-origin”标头
【发布时间】:2021-11-18 08:06:30
【问题描述】:

我必须从受资源服务器保护的浏览器中使用访问令牌调用 API,并使用 spring boot 2.4.6

GET API - http://127.0.0.1:9090/api/user/benz@gmail.com

当我调用上述 API 时,浏览器会抛出以下 CORS 阻塞异常

No 'access-control-allow-origin' header is present on the requested resource

WebSecurityConfig

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

    private AuthEntryPoint authEntryPoint;

    public WebSecurityConfig(AuthEntryPoint authEntryPoint){
        this.authEntryPoint=authEntryPoint;
    }



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().exceptionHandling().authenticationEntryPoint(authEntryPoint)
                .and().authorizeRequests().antMatchers("/api/contact").permitAll()
                .and().authorizeRequests().antMatchers("/api/forget/**").permitAll()
                .and().authorizeRequests().antMatchers("/api/user/register","/api/user/login").permitAll()
                .and().authorizeRequests().anyRequest().authenticated()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/api/contact")
        .antMatchers("/api/forget/**")
                .antMatchers("/api/user/register","/api/user/login");
    }

}

交叉配置

@Configuration
public class CrossConfig {

     @Bean
     public WebMvcConfigurer crossConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
              registry.addMapping("/**").allowedMethods("GET","POST","PUT","DELETE","OPTIONS")
                      .allowedHeaders("*");
            }
        };
     }
}

资源服务器配置

@Configuration
@EnableResourceServer
@EnableConfigurationProperties(SecurityProperties.class)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
      /............./
}

控制器

@CrossOrigin(origins = "*",maxAge = 3600)
@RestController
@RequestMapping("/api/user")
public class VoyageUserController {

    private VoyageUserService voyageUserService;

    public VoyageUserController(VoyageUserService voyageUserService){
        this.voyageUserService=voyageUserService;
    }

    @GetMapping(value = "/{id}",produces = {MediaType.APPLICATION_JSON_VALUE})
    @PreAuthorize("hasAnyRole('ROLE_USER','ROLE_MODERATOR','ROLE_ADMIN')")
    public ResponseEntity<VoyageUserResponse> getUser(@PathVariable("id") String email){
          return (email.trim().isEmpty()) ?
                  new ResponseEntity<>(HttpStatus.BAD_REQUEST) :
                  new ResponseEntity<>(voyageUserService.findVoyageUser(email),HttpStatus.OK);
    }
}

使用 Axios 来自 React 的 API 请求

if(email){
    axios.get(`http://127.0.0.1:9090/api/user/${email}`,{
        headers:{
     'Authorization':'bearer '+token}
    })
    .then(res=>{
        const userDetail = res.data;
        console.log(userDetail);
       this.setState({
           voyageUser:userDetail
       });
      this.setIsLogged(true);
    }).catch(error=>{
        console.log(error);
        this.setIsLogged(false);
    });
   }

我已经完成了 StackOverflow 作为答案中可用的所有事情,但是浏览器仍然会引发 CORS 阻塞异常。

注意 - 我的代码中没有语法错误,如果问题包含某些内容,请忽略。

【问题讨论】:

    标签: java reactjs spring spring-boot spring-security


    【解决方案1】:

    已解决 - 问题被确定为ResourceServerConfig 类在WebSecurityConfig 类之前加载,这是导致CORS 错误的原因,所以我决定在ResourceServerConfig 中进行授权配置类。

    资源服务器配置

    @Configuration
    @EnableResourceServer
    @EnableConfigurationProperties(SecurityProperties.class)
    public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    
        @Autowired
        private AuthEntryPoint authEntryPoint;
    
     @Override
        public void configure(HttpSecurity http) throws Exception {
            http.cors().configurationSource(corsConfigurationSource()).and().csrf().disable().exceptionHandling().authenticationEntryPoint(authEntryPoint)
                    .and().authorizeRequests().antMatchers("/api/contact").permitAll()
                    .and().authorizeRequests().antMatchers("/api/forget/**").permitAll()
                    .and().authorizeRequests().antMatchers("/api/user/register","/api/user/login").permitAll()
                    .and().authorizeRequests().anyRequest().authenticated()
                    .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }
    
    
        public CorsConfigurationSource corsConfigurationSource() {
            CorsConfiguration configuration = new CorsConfiguration();
            configuration.setAllowedOrigins(Arrays.asList("*"));
            configuration.addAllowedHeader("*");
            configuration.addAllowedMethod("*");
            configuration.setAllowCredentials(true);
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", configuration);
            return source;
        }
    
    }
    

    WebSecurityConfig

    @EnableGlobalMethodSecurity(prePostEnabled = true)
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    }
    

    它适用于没有CORS错误的浏览器

    【讨论】:

      猜你喜欢
      • 2019-08-12
      • 2018-03-05
      • 2017-10-08
      • 2019-01-28
      • 2020-07-10
      • 2016-06-30
      • 2016-10-08
      相关资源
      最近更新 更多