Handshake failed due to invalid Upgrade header: null
昨天用 Chrome 的 Simple WebSocket Client 測試用 Spring Framework 開發的 WebSocket 程式時,發現一直吐出 org.springframework.web.socket.server.support.DefaultHandshakeHandler.handleInvalidUpgradeHeader Handshake failed due to invalid Upgrade header: null
的錯誤訊息。但是用 Wireshark 抓封包看到送出的 Request 其實是有 Upgrade: websocket
。
用 Google 大神找不到有用的解法,原始的 log 也看不出什麼有用的資訊。打開 Spring 的 debug log 後看到了個似乎相關的訊息:OriginHandshakeInterceptor - Handshake request rejected, Origin header value chrome-extension://pfdhoblngboilpfeibdedpjgfnlcodoo not allowed
。查了文件發現原來 Spring 預設只允許相同來源的 Request,但是 Simple WebSocket Client 送出的是 Origin: chrome-extension://pfdhoblngboilpfeibdedpjgfnlcodoo
,所以就被擋掉了。為了測試只好設 allowed-origins="*"
,設好後重啟就可以用了。
詳細的設定可以參考 Spring 官方文件的 Configuring allowed origins
English Version
While testing my Spring-based WebSocket application using Simple WebSocket Client, server log keeps saying org.springframework.web.socket.server.support.DefaultHandshakeHandler.handleInvalidUpgradeHeader Handshake failed due to invalid Upgrade header: null
. However, packets captured by Wireshark indeed contains Upgrade: websocket
.
No luck with Google, and the log show nothing useful. Forced to turn on Spring debug log, something suspicious appears: OriginHandshakeInterceptor - Handshake request rejected, Origin header value chrome-extension://pfdhoblngboilpfeibdedpjgfnlcodoo not allowed
. According to the reference, it turns out that Spring by default allows only same origin requests. That’s why the request is denied since Simple WebSocket Client sends out Origin: chrome-extension://pfdhoblngboilpfeibdedpjgfnlcodoo
. After setting allowed-origins="*"
, everything works!
Detail setting can be found in Configuring allowed origins.