gpt4 book ai didi

grails - 即使允许,grails 3 CORS返回403

转载 作者:行者123 更新时间:2023-12-02 14:06:07 26 4
gpt4 key购买 nike

我已通过以下命令在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);
}

问题是请求正确响应,
但是如果请求的 header 为“Origin”,则请求返回403

即使响应 header 是:
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
}

关于grails - 即使允许,grails 3 CORS返回403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42460853/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com