Spring CORS controller annotation not working

时光总嘲笑我的痴心妄想 提交于 2020-01-12 15:12:14

问题


I want to allow cross origin requests for one domain. My project uses Spring so I want to take advantage of the new CORS support.

I am using version 4.2.0 for all springframework dependencies.

I followed the example here https://spring.io/blog/2015/06/08/cors-support-in-spring-framework#disqus_thread and tried the first version. My controller annotations looks like:

@CrossOrigin(origins = "http://fiddle.jshell.net/", maxAge = 3600)
@Controller
@RequestMapping("/rest")
public class MyController 

If I understood correctly the mvc-config is an alternative method. I tried it as well:

<mvc:cors>  
    <mvc:mapping path="/**"
        allowed-origins="http://fiddle.jshell.net/, http://domain2.com"
        allowed-methods="GET, PUT"
        allowed-headers="header1, header2, header3"
        exposed-headers="header1, header2" allow-credentials="false"
        max-age="123" />    
</mvc:cors>

With either methods, the Response doesn't seem to contain anything like Access-Control-Allow-Origin, neither can I get a result back through a simple query from jsfiddle.

The header info from Chrome developer tools, when ran and accessed from localhost is below. In this case the request is from the same domain and not through javascript, but I thought the CORS annotation would add the access control parameters anyway?

Response Headers:

Content-Length:174869 
Content-Type:text/html;charset=UTF-8 
Date:Fri, 21 Aug 2015 12:21:09 GMT 
Server:Apache-Coyote/1.1

Request Header:

      Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*\/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,ro;q=0.6,de;q=0.4,fr;q=0.2
Cache-Control:no-cache 
Connection:keep-alive
Cookie:JSESSIONID=831EBC138D2B7E176DF4945ADA05CAC1;_ga=GA1.1.1046500342.1404228238; undefined=0 
Host:localhost:8080 
Pragma:no-cache 
Upgrade-Insecure-Requests:1 
User-Agent:Mozilla/5.0(Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36

I do not use spring boot and I presume I missed a configuration step.


回答1:


I've reproduced this problem for myself. The problem happens when I don't have @EnableWebMvc annotation in my @Configuration annotated class. I've reported this problem as a bug in Sping Jira with details behind it: https://jira.spring.io/browse/SPR-13857

I see the fix either in code or in documentation. Documentation fix would be to state in @CrossOrigin class javadoc that @EnableWebMvc is required, but I'd prefer the fix in code so that cors annotation works without @EnableWebMvc.




回答2:


Could you try with "http://fiddle.jshell.net" instead of "http://fiddle.jshell.net/"?



来源:https://stackoverflow.com/questions/32140706/spring-cors-controller-annotation-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!