问题陈述:
我正在尝试使用Golang中的基本中间件(如the WebSocket protocol doesn’t handle authorization or authentication)来保护websocket升级程序http端点。
社区建议
策略:
到目前为止,我失败的策略是尝试上述社区策略1通过中间件安全地升级与自定义标头X-Api-Key
的连接,并且仅升级使用匹配密钥发起对话的客户端。
下面的代码在服务器端产生the client is not using the websocket protocol: 'upgrade' token not found in 'Connection' header
。
询问:
我想寻求帮助以了解情况:
GET
,服务器拒绝了通过方案ws
进行的后续升级请求。想法和建议,示例,要点表示赞赏,如果我可以进一步澄清或重申,请提出建议。
server.go:
package main
import (
"flag"
"log"
"net/http"
"github.com/gorilla/websocket"
)
func main() {
var addr = flag.String("addr", "localhost:8080", "http service address")
flag.Parse()
http.Handle("/ws", Middleware(
http.HandlerFunc(wsHandler),
authMiddleware,
))
log.Printf("listening on %v", *addr)
log.Fatal(http.ListenAndServe(*addr, nil))
}
func Middleware(h http.Handler, middleware ...func(http.Handler) http.Handler) http.Handler {
for _, mw := range middleware {
h = mw(h)
}
return h
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func wsHandler(rw http.ResponseWriter, req *http.Request) {
wsConn, err := upgrader.Upgrade(rw, req, nil)
if err != nil {
log.Printf("upgrade err: %v", err)
return
}
defer wsConn.Close()
for {
_, message, err := wsConn.ReadMessage()
if err != nil {
log.Printf("read err: %v", err)
break
}
log.Printf("recv: %s", message)
}
}
func authMiddleware(next http.Handler) http.Handler {
TestApiKey := "test_api_key"
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
var apiKey string
if apiKey = req.Header.Get("X-Api-Key"); apiKey != TestApiKey {
log.Printf("bad auth api key: %s", apiKey)
rw.WriteHeader(http.StatusForbidden)
return
}
next.ServeHTTP(rw, req)
})
}
client.go:
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"github.com/gorilla/websocket"
)
func main() {
// auth first
req, err := http.NewRequest("GET", "http://localhost:8080/ws", nil)
if err != nil {
log.Fatal(err)
}
req.Header.Set("X-Api-Key", "test_api_key")
resp, err := http.DefaultClient.Do(req)
if err != nil || resp.StatusCode != http.StatusOK {
log.Fatalf("auth err: %v", err)
}
defer resp.Body.Close()
// create ws conn
u := url.URL{Scheme: "ws", Host: "localhost:8080", Path: "/ws"}
u.RequestURI()
fmt.Printf("ws url: %s", u.String())
log.Printf("connecting to %s", u.String())
conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatalf("dial err: %v", err)
}
err = conn.WriteMessage(websocket.TextMessage, []byte("hellow websockets"))
if err != nil {
log.Fatalf("msg err: %v", err)
}
}
答案 0 :(得分:1)
问题中的客户端应用程序将两个请求发送到websocket端点。第一个是经过身份验证的HTTP请求。此请求不是网络套接字握手,因此升级失败。第二个请求是未经身份验证的Websocket握手。该请求失败,因为它无法通过身份验证。
解决方法是发送经过身份验证的Websocket握手。通过最后一个参数将auth标头传递给Dial。
func main() {
u := url.URL{Scheme: "ws", Host: "localhost:8080", Path: "/ws"}
conn, _, err := websocket.DefaultDialer.Dial(u.String(), http.Header{"X-Api-Key": []string{"test_api_key"}})
if err != nil {
log.Fatalf("dial err: %v", err)
}
err = conn.WriteMessage(websocket.TextMessage, []byte("hellow websockets"))
if err != nil {
log.Fatalf("msg err: %v", err)
}
}
在服务器上,使用用于验证HTTP请求的应用程序代码来验证握手。