如何允许跨源请求

时间:2017-11-14 09:01:18

标签: java spring rest spring-boot

我是一名后端开发人员,我正在提供一个带有JWT安全性的spring boot rest API,供前端开发人员使用,该开发人员从本地host调用api。因此,当他调用POST请求时,他说他收到了CORS错误。所以我添加了部分

 @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {


        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");


        chain.doFilter(request, response);
    }

但他仍然得到错误。可能是什么原因。感谢任何帮助

OPTIONS https:my.domain/url 401 (Unauthorized)

当它是POST请求时。

控制器代码:

@RestController
public class RegistrationController {



    @Autowired
    @Qualifier("restTemplateUserRegitration")
    private RestTemplate restTemplateUserRegitration;
@RequestMapping(value="${user.endpoint}",produces={MediaType.APPLICATION_JSON_VALUE},method=RequestMethod.POST)
    public ResponseEntity<?> registerUser(@RequestBody Model ModelRequest){

                Map<String, Object> Status=new HashMap<String, Object>();
                FeedBackStatus = restTemplateUserRegitration.postForObject("http:serviceurl",registration/single",Model.class,Map.class );
                return ResponseEntity.ok(Status); 
    }
}

5 个答案:

答案 0 :(得分:1)

我也有类似的经历。我们已经解决了以下问题。 此代码添加在securityConfiguration中。 浏览器将在发送POST请求之前首先发送OPTIONS请求。因此,当发送请求时,授权标头值不包含在请求标头中,因此JWT过滤器判断用户未经身份验证。

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring()
            .antMatchers(HttpMethod.OPTIONS);
}

答案 1 :(得分:0)

首先尝试这个,这应该允许所有来源,但这是安全风险。

response.setHeader("Access-Control-Allow-Origin", "*");

答案 2 :(得分:0)

这是一个选择。不确定它是否优雅

 @Bean
  public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
  }

把它放在任何一个春豆里。

答案 3 :(得分:0)

您可以创建自己的CorsConfiguration

@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {

CorsConfigurationSource corsConfigurationSource = new CorsConfigurationSource() {
    @Override
    public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("http://localhost:63342");
        corsConfiguration.addAllowedHeader("Authorization");
        corsConfiguration.setAllowedMethods(Arrays.asList("POST", "GET"));
        corsConfiguration.setMaxAge(3600L);
        return corsConfiguration;
    }
};

并将其添加到配置中。

.and().cors().configurationSource(corsConfigurationSource);

尝试使用此注释

@CrossOrigin

答案 4 :(得分:-1)

您应该实现这样的过滤器:

let mydiv = document.createElement('div');
mydiv.innerHTML = "<div> <p>Intro</p> </div> <div id='greet'> <p>Hello Example</p> </div>";
console.log(mydiv.getElementByID("greet"))

从帖子Cross Origin Request Blocked Spring MVC Restful Angularjs

中找到此信息

希望这有帮助!