grails 3 CORS returning 403 even though it's allowed

淺唱寂寞╮ 提交于 2020-01-01 18:53:10

问题


I've allowed cors in my grails 3 application through :

cors:
     enabled: true

and added the filter :

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

The problem is the request is responding correctly, but if the request has a header 'Origin', the request returns 403

even though the response header is :

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

Any idea how to solve this ?

Thanks


回答1:


The issue was with websocket, since my error was happening with the url containing /stomp/info

The solution was to add the following class

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

}

and then add it to resources.groovy

beans = {
    websocketConfig WebSocketConfig
}


来源:https://stackoverflow.com/questions/42460853/grails-3-cors-returning-403-even-though-its-allowed

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