圣杯 3 CORS 返回 403,即使允许

  • 本文关键字:CORS 返回 圣杯 grails cors
  • 更新时间 :
  • 英文 :


我已经在我的Grails 3应用程序中允许CORS:

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);
    }

问题是请求正在正确响应,但是,如果请求具有"原点",请求将返回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

的URL发生

解决方案是添加以下类

@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
}

最新更新