[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"academy-blogs-en-1-1-all-go-websocket-security-session-authentication-all--*":3,"academy-blog-translations-sqru15ayawxuodh":139},{"data":4,"page":127,"perPage":127,"totalItems":127,"totalPages":127},[5],{"alt":6,"collectionId":7,"collectionName":8,"content":9,"cover_image":10,"cover_image_path":11,"created":12,"created_by":13,"expand":14,"id":133,"keywords":134,"locale":109,"published_at":135,"scheduled_at":13,"school_blog":131,"short_description":136,"slug":137,"status":129,"title":6,"updated":138,"updated_by":13,"views":132},"Ep.23 Go and WebSocket Security - Enhancing Security with Session and Authentication!","sclblg987654321","school_blog_translations","\u003Cp class=\"p1\">\u003Cstrong>Go and WebSocket Security - Enhancing Security with Session and Authentication!\u003C\u002Fstrong>\u003C\u002Fp>\u003Cp class=\"p2\">&nbsp;\u003C\u002Fp>\u003Cp class=\"p3\">\u003Cstrong>Why Use Session and Authentication with WebSocket?\u003C\u002Fstrong>\u003Cbr>WebSocket does not automatically send Credential data (such as Tokens or Cookies) like HTTP does. Therefore, we need a way to authenticate users each time a connection is made to ensure that only authorized users can communicate with the server.\u003C\u002Fp>\u003Cp class=\"p2\">&nbsp;\u003C\u002Fp>\u003Cp class=\"p3\">\u003Cstrong>How to Add Authentication to WebSocket\u003C\u002Fstrong>\u003C\u002Fp>\u003Cp class=\"p3\">1. Check the Token or Cookie before allowing the connection.\u003C\u002Fp>\u003Cp class=\"p3\">2. Store the connection state in a Session to identify the user.\u003C\u002Fp>\u003Cp class=\"p3\">3. Verify the user's permissions for every message sent.\u003C\u002Fp>\u003Cp class=\"p2\">&nbsp;\u003C\u002Fp>\u003Cp class=\"p3\">\u003Cstrong>Steps to Add Authentication to WebSocket\u003C\u002Fstrong>\u003C\u002Fp>\u003Cp class=\"p3\">1. Check the Token before allowing the connection.\u003Cbr>In the WebSocket connection upgrade process, the Token can be checked from the Request Header.\u003Cbr>In this example :\u003Cbr>Use authMiddleware to check the Token in the Request Header before allowing the connection.\u003Cbr>If the Token is invalid, return a 401 (Unauthorized) status.\u003Cbr>Example code :\u003C\u002Fp>\u003Cpre>\u003Ccode class=\"language-plaintext\">package main\r\n\r\nimport (\r\n    \"fmt\"\r\n    \"net\u002Fhttp\"\r\n\r\n    \"github.com\u002Fgorilla\u002Fwebsocket\"\r\n)\r\n\r\nvar upgrader = websocket.Upgrader{\r\n    CheckOrigin: func(r *http.Request) bool {\r\n        return true\r\n    },\r\n}\r\n\r\nfunc authMiddleware(next http.HandlerFunc) http.HandlerFunc {\r\n    return func(w http.ResponseWriter, r *http.Request) {\r\n        token := r.Header.Get(\"Authorization\")\r\n        if token != \"valid-token\" {\r\n            http.Error(w, \"Unauthorized\", http.StatusUnauthorized)\r\n            return\r\n        }\r\n        next(w, r)\r\n    }\r\n}\r\n\r\nfunc handleConnections(w http.ResponseWriter, r *http.Request) {\r\n    conn, err := upgrader.Upgrade(w, r, nil)\r\n    if err != nil {\r\n        fmt.Println(\"Error upgrading connection:\", err)\r\n        return\r\n    }\r\n    defer conn.Close()\r\n\r\n    for {\r\n        _, msg, err := conn.ReadMessage()\r\n        if err != nil {\r\n            fmt.Println(\"Error reading message:\", err)\r\n            break\r\n        }\r\n        fmt.Printf(\"Received: %s\\n\", msg)\r\n    }\r\n}\r\n\r\nfunc main() {\r\n    http.HandleFunc(\"\u002Fws\", authMiddleware(handleConnections))\r\n\r\n    fmt.Println(\"WebSocket server started at :8080\u002Fws\")\r\n    http.ListenAndServe(\":8080\", nil)\r\n}\r\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp class=\"p2\">&nbsp;\u003C\u002Fp>\u003Cp class=\"p3\">2. Use Session to Store User Information.\u003Cbr>You can use a map or Session Manager to keep track of each user's connection state.\u003Cbr>In this example :\u003Cbr>Use the Token as a Key in sessions to identify each user's connection.\u003Cbr>When the connection is closed, remove the Token from sessions.\u003Cbr>Example :\u003C\u002Fp>\u003Cpre>\u003Ccode class=\"language-plaintext\">var sessions = make(map[string]*websocket.Conn)\r\n\r\nfunc handleConnections(w http.ResponseWriter, r *http.Request) {\r\n    token := r.Header.Get(\"Authorization\")\r\n    conn, err := upgrader.Upgrade(w, r, nil)\r\n    if err != nil {\r\n        fmt.Println(\"Error upgrading connection:\", err)\r\n        return\r\n    }\r\n    defer conn.Close()\r\n\r\n    sessions[token] = conn\r\n    defer delete(sessions, token)\r\n\r\n    for {\r\n        _, msg, err := conn.ReadMessage()\r\n        if err != nil {\r\n            fmt.Println(\"Error reading message:\", err)\r\n            break\r\n        }\r\n        fmt.Printf(\"Received from %s: %s\\n\", token, msg)\r\n    }\r\n}\r\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp class=\"p2\">&nbsp;\u003C\u002Fp>\u003Cp class=\"p3\">3. Check Permissions for Every Message Sent.\u003Cbr>If you want to verify permissions for each message sent, you can add logic in the ReadMessage function.\u003Cbr>Example :\u003C\u002Fp>\u003Cpre>\u003Ccode class=\"language-plaintext\">func handleConnections(w http.ResponseWriter, r *http.Request) {\r\n    token := r.Header.Get(\"Authorization\")\r\n    conn, err := upgrader.Upgrade(w, r, nil)\r\n    if err != nil {\r\n        fmt.Println(\"Error upgrading connection:\", err)\r\n        return\r\n    }\r\n    defer conn.Close()\r\n\r\n    sessions[token] = conn\r\n    defer delete(sessions, token)\r\n\r\n    for {\r\n        _, msg, err := conn.ReadMessage()\r\n        if err != nil {\r\n            fmt.Println(\"Error reading message:\", err)\r\n            break\r\n        }\r\n\r\n        \u002F\u002F ตัวอย่างการตรวจสอบสิทธิ์ในข้อความ\r\n        if string(msg) == \"admin-only-action\" &amp;&amp; token != \"admin-token\" {\r\n            conn.WriteMessage(websocket.TextMessage, []byte(\"Unauthorized action\"))\r\n            continue\r\n        }\r\n\r\n        fmt.Printf(\"Message from %s: %s\\n\", token, msg)\r\n    }\r\n}\r\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp class=\"p4\">&nbsp;\u003C\u002Fp>\u003Cp class=\"p3\">\u003Cstrong>Real-World Use Case: Sending Data to Specific User Groups\u003C\u002Fstrong>\u003Cbr>You can send data to specific groups, such as Admin groups or specific users, by using Tokens or Roles as filters.\u003Cbr>Example :\u003C\u002Fp>\u003Cpre>\u003Ccode class=\"language-plaintext\">func broadcastToAdmins(message string) {\r\n    for token, conn := range sessions {\r\n        if token == \"admin-token\" { \u002F\u002F ตัวอย่างการกรองเฉพาะ Admin\r\n            conn.WriteMessage(websocket.TextMessage, []byte(message))\r\n        }\r\n    }\r\n}\r\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp class=\"p2\">&nbsp;\u003C\u002Fp>\u003Cp class=\"p3\">\u003Cstrong>In Summary\u003C\u002Fstrong>\u003C\u002Fp>\u003Cul class=\"ul1\">\u003Cli class=\"li3\">Use Middleware to check the Token before allowing the connection.\u003C\u002Fli>\u003Cli class=\"li3\">Store the user's connection state in a Session for future use.\u003C\u002Fli>\u003Cli class=\"li3\">Add permission-checking logic for every message sent to enhance security.\u003C\u002Fli>\u003C\u002Ful>","16_11zon_cp1kgvj98a.webp","https:\u002F\u002Ftwsme-r2.tumwebsme.com\u002Fsclblg987654321\u002Fsfm9rjserjk3s7g\u002F16_11zon_cp1kgvj98a.webp","2026-03-04 08:34:21.089Z","",{"keywords":15,"locale":103,"school_blog":113},[16,23,28,33,38,43,48,53,58,63,68,73,78,83,88,93,98],{"collectionId":17,"collectionName":18,"created":19,"created_by":13,"id":20,"name":21,"updated":22,"updated_by":13},"sclkey987654321","school_keywords","2026-03-04 08:20:11.547Z","ey3puyme01a9bsw","Go","2026-04-10 16:07:25.893Z",{"collectionId":17,"collectionName":18,"created":24,"created_by":13,"id":25,"name":26,"updated":27,"updated_by":13},"2026-03-04 08:33:59.315Z","btmgtfwmgpke1aa","Go language","2026-04-10 16:08:04.625Z",{"collectionId":17,"collectionName":18,"created":29,"created_by":13,"id":30,"name":31,"updated":32,"updated_by":13},"2026-03-04 08:20:14.253Z","ah6lvy4x8qe08l5","Golang","2026-04-10 16:07:26.172Z",{"collectionId":17,"collectionName":18,"created":34,"created_by":13,"id":35,"name":36,"updated":37,"updated_by":13},"2026-03-04 08:34:00.920Z","ecac9y661or1xka","WebSocket","2026-04-10 16:08:05.227Z",{"collectionId":17,"collectionName":18,"created":39,"created_by":13,"id":40,"name":41,"updated":42,"updated_by":13},"2026-03-04 08:34:18.714Z","7cb29z95923lmhe","authentication","2026-04-10 16:08:11.822Z",{"collectionId":17,"collectionName":18,"created":44,"created_by":13,"id":45,"name":46,"updated":47,"updated_by":13},"2026-03-04 08:34:19.423Z","y65daawikvzcgx8","user authorization","2026-04-10 16:08:12.072Z",{"collectionId":17,"collectionName":18,"created":49,"created_by":13,"id":50,"name":51,"updated":52,"updated_by":13},"2026-03-04 08:34:01.321Z","gjlkrd1oymyuvn2","security","2026-04-10 16:08:05.316Z",{"collectionId":17,"collectionName":18,"created":54,"created_by":13,"id":55,"name":56,"updated":57,"updated_by":13},"2026-03-04 08:34:19.080Z","6yuww25itmg98su","Session","2026-04-10 16:08:11.911Z",{"collectionId":17,"collectionName":18,"created":59,"created_by":13,"id":60,"name":61,"updated":62,"updated_by":13},"2026-03-04 08:19:55.412Z","hz7yzm54i2o6cl7","web development","2026-04-10 16:07:24.402Z",{"collectionId":17,"collectionName":18,"created":64,"created_by":13,"id":65,"name":66,"updated":67,"updated_by":13},"2026-03-04 08:32:15.843Z","m0x7wo77i8iycf1","Programming Education","2026-04-10 16:07:51.675Z",{"collectionId":17,"collectionName":18,"created":69,"created_by":13,"id":70,"name":71,"updated":72,"updated_by":13},"2026-03-04 08:32:51.346Z","tmzmy6jyz1n35rr","Go Programming","2026-04-10 16:08:01.434Z",{"collectionId":17,"collectionName":18,"created":74,"created_by":13,"id":75,"name":76,"updated":77,"updated_by":13},"2026-03-04 08:31:22.575Z","lfjse4xivbgg5wu","Practice programming","2026-04-10 16:07:39.541Z",{"collectionId":17,"collectionName":18,"created":79,"created_by":13,"id":80,"name":81,"updated":82,"updated_by":13},"2026-03-04 08:20:33.316Z","ln1ntwattzmxo0o","programming","2026-04-10 16:07:27.299Z",{"collectionId":17,"collectionName":18,"created":84,"created_by":13,"id":85,"name":86,"updated":87,"updated_by":13},"2026-03-04 08:32:26.073Z","vnvj1oaxje9m1q8","programming for beginners","2026-04-10 16:07:54.133Z",{"collectionId":17,"collectionName":18,"created":89,"created_by":13,"id":90,"name":91,"updated":92,"updated_by":13},"2026-03-04 08:31:49.362Z","2m9vv13etpn6zkx","programming language","2026-04-10 16:07:45.606Z",{"collectionId":17,"collectionName":18,"created":94,"created_by":13,"id":95,"name":96,"updated":97,"updated_by":13},"2026-03-04 08:31:54.955Z","264sfjffyhspetq","programmers","2026-04-10 16:07:47.221Z",{"collectionId":17,"collectionName":18,"created":99,"created_by":13,"id":100,"name":101,"updated":102,"updated_by":13},"2026-03-04 08:26:59.195Z","gab60xd583s3qaw","Superdev School","2026-04-10 16:07:37.087Z",{"code":104,"collectionId":105,"collectionName":106,"created":107,"flag":108,"id":109,"is_default":110,"label":111,"updated":112},"en","pbc_1989393366","locales","2026-01-22 11:00:02.726Z","twemoji:flag-united-states","qv9c1llfov2d88z",false,"English","2026-04-10 15:42:46.825Z",{"category":114,"collectionId":115,"collectionName":116,"expand":117,"id":131,"views":132},"wqxt7ag2gn7xcmk","pbc_2105096300","school_blogs",{"category":118},{"blogIds":119,"collectionId":120,"collectionName":121,"created":122,"created_by":13,"id":114,"image":123,"image_alt":13,"image_path":124,"label":125,"name":126,"priority":127,"publish_at":128,"scheduled_at":13,"status":129,"updated":130,"updated_by":13},[],"sclcatblg987654321","school_category_blogs","2026-03-04 08:33:53.210Z","59ty92ns80w_15oc1implw.png","https:\u002F\u002Ftwsme-r2.tumwebsme.com\u002Fsclcatblg987654321\u002Fwqxt7ag2gn7xcmk\u002F59ty92ns80w_15oc1implw.png",{"en":126,"th":126},"Golang The Series",1,"2026-03-16 04:39:38.440Z","published","2026-04-25 02:32:15.470Z","sqru15ayawxuodh",266,"sfm9rjserjk3s7g",[20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100],"2025-01-27 04:40:32.810Z","Learn how to enhance WebSocket security in Go using Session and user authentication methods.","go-websocket-security-session-authentication","2026-04-25 02:47:31.409Z",{"en":137}]