grails 3 Cor返回403,尽管它';允许
我通过以下方式在grails 3应用程序中允许cors:grails 3 Cor返回403,尽管它';允许,grails,cors,Grails,Cors,我通过以下方式在grails 3应用程序中允许cors: cors: enabled: true 并添加了过滤器: public CorsFilter() { } @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws ServletException, IOExc
cors:
enabled: true
并添加了过滤器:
public CorsFilter() { }
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain)
throws ServletException, IOException {
String origin = req.getHeader("Origin");
boolean options = "OPTIONS".equals(req.getMethod());
if (options) {
if (origin == null) return;
resp.addHeader("Access-Control-Allow-Headers", "origin, authorization, accept, content-type, x-requested-with");
resp.addHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS");
resp.addHeader("Access-Control-Max-Age", "3600");
}
resp.addHeader("Access-Control-Allow-Origin", origin == null ? "*" : origin);
resp.addHeader("Access-Control-Allow-Credentials", "true");
if (!options) chain.doFilter(req, resp);
}
问题是请求响应正确,
但是,如果请求具有标题“Origin”,则请求返回403
即使响应头是:
Access-Control-Allow-Credentials →true
Access-Control-Allow-Origin →http://localhost:4200
Cache-Control →no-store, no-cache, must-revalidate, max-age=0
Content-Length →0
Date →Sat, 25 Feb 2017 19:44:21 GMT
X-Application-Context →application:development
你知道怎么解决这个问题吗
谢谢问题出在websocket上,因为我的错误发生在包含
/stomp/info
解决方案是添加以下类
@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
void configureMessageBroker(MessageBrokerRegistry messageBrokerRegistry) {
messageBrokerRegistry.enableSimpleBroker "/queue", "/hmi"
messageBrokerRegistry.setApplicationDestinationPrefixes "/app"
}
@Override
void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
stompEndpointRegistry.addEndpoint("/stomp","/hmi","/hmi/status").setAllowedOrigins("*").withSockJS()
}
@Bean
GrailsSimpAnnotationMethodMessageHandler grailsSimpAnnotationMethodMessageHandler(
MessageChannel clientInboundChannel,
MessageChannel clientOutboundChannel,
SimpMessagingTemplate brokerMessagingTemplate
) {
def handler = new GrailsSimpAnnotationMethodMessageHandler(clientInboundChannel, clientOutboundChannel, brokerMessagingTemplate)
handler.destinationPrefixes = ["/app"]
return handler
}
}
然后将其添加到resources.groovy
beans = {
websocketConfig WebSocketConfig
}
你在使用spring安全性吗?不,这是一个完全没有安全性的项目。但这是一个rest配置文件,不知道这个配置文件是否有特殊的smthg,为什么要注册自己的过滤器?grails.cors.enabled=true为您注册一个过滤器我在没有过滤器的情况下尝试了它,我也遇到了同样的错误。这就是为什么我认为我也应该添加itI的原因。我应该注意,过滤器实际上是在工作的,因为在响应头中,我得到了
访问控制允许源代码,但我仍然得到403,如果我从请求中删除头文件“Origin”,它就工作了