Spring @CrossOrigin无效

时间:2016-03-25 19:23:18

标签: java spring spring-mvc cors cross-domain

我正在使用spring-web为我的网络/移动应用程序构建json / rest后端。 我正在使用javax.servlet.Filter,添加适当的cors头:

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, accept, authorization, content-type");
        response.setHeader("X-Frame-Options", "SAMEORIGIN");
        chain.doFilter(req, res);
    }

现在我正在尝试升级到spring 4.2.5并使用@CrossOrigin注释,但似乎OPTION调度的响应不包含适当的标头。

这是我的配置:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "it.foo.api.rest", useDefaultFilters = false, 
    includeFilters = @ComponentScan.Filter(value = Controller.class, type = FilterType.ANNOTATION))
public class WebConfig extends WebMvcConfigurerAdapter {

    ...

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
//          .allowCredentials(true)
//          .allowedOrigins("*")
//          .maxAge(3600)
//          .allowedMethods("PUT", "POST", "GET", "OPTIONS", "DELETE")
//          .allowedHeaders("content-type", "authorization", "x-requested-with", "accept", "origin", "Access-Control-Request-Method", "Access-Control-Request-Headers")
//          .exposedHeaders("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials");
//          .exposedHeaders("x-requested-with, accept, authorization, content-type");
    }

你可以看到我尝试了一些配置。

我的控制器:

@CrossOrigin(allowCredentials="true", 
    methods={RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT,RequestMethod.OPTIONS,RequestMethod.DELETE},
    allowedHeaders={"x-requested-with", "accept", "authorization", "content-type"}, 
    exposedHeaders={"access-control-allow-headers", "access-control-allow-methods", "access-control-allow-origin", "access-control-max-age", "X-Frame-Options"})
@RestController
@RequestMapping(value="/admin")
public class AdminUserController extends BaseController {


    @RequestMapping(value = "/login", method = RequestMethod.POST,  produces = MediaType.APPLICATION_JSON_VALUE)
    public HttpEntity<AdminUserResource> postLogin(@RequestBody AdminLoginCredentials credentials) {
        return new ResponseEntity<AdminUserResource>(..., HttpStatus.OK);
    }

我再次测试了几个配置,只有基本的@CrossOrigin注释。

带有servlet过滤器的标头(旧版本):enter image description here

标题没有过滤器和WITH @CrossOrigin(新版本,不能正常工作):enter image description here

我找不到我错过的东西!

0 个答案:

没有答案