[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"academy-blog-translations-none":3,"academy-blogs-en-1-1-all-websocket-chat-authentication-jwt-all--*":4},{},{"data":5,"meta":91},[6],{"categoryId":7,"collectionId":8,"collectionName":9,"content":10,"createBy":11,"createDate":12,"created":13,"description":14,"expand":15,"group":83,"id":83,"image":84,"imageAlt":85,"imagePath":86,"keywordIds":87,"langId":79,"publishDate":36,"scheduleDate":12,"slug":88,"status":28,"title":85,"updateBy":11,"updated":89,"views":90},"wqxt7ag2gn7xcmk","sclblg987654321","school_blog","\u003Ch2>Why Add Authentication to WebSocket Chat?\u003C\u002Fh2>\u003Cp>Using WebSocket in a chat system allows for real-time message exchange, but without an authentication system, anyone can access the chat without logging in. This can lead to security issues such as:\u003C\u002Fp>\u003Cul>\u003Cli>Unauthorized individuals can eavesdrop or send messages.\u003C\u002Fli>\u003Cli>Access permissions for individual users cannot be restricted.\u003C\u002Fli>\u003Cli>There is no verification of the identity of the message sender.\u003C\u002Fli>\u003C\u002Ful>\u003Cp>Therefore, using JWT (JSON Web Token) for authentication and controlling access permissions in WebSocket is a suitable approach.\u003C\u002Fp>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch3>Structure of the Authentication System in WebSocket Chat\u003C\u002Fh3>\u003Col>\u003Cli>User Authentication - Users log in and receive a JWT Token.\u003C\u002Fli>\u003Cli>WebSocket Server - Validates the Token before allowing connections.\u003C\u002Fli>\u003Cli>GraphQL API - Uses JWT to identify users when sending and receiving messages.\u003C\u002Fli>\u003Cli>Database (PostgreSQL \u002F MongoDB) - Stores user account information and messages.\u003C\u002Fli>\u003C\u002Fol>\u003Ch3>\u003Cbr>Install Necessary Libraries\u003C\u002Fh3>\u003Cpre>\u003Ccode class=\"language-plaintext\">go get github.com\u002Fdgrijalva\u002Fjwt-go\ngo get github.com\u002Fgorilla\u002Fwebsocket\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch3>Creating User Authentication with JWT\u003C\u002Fh3>\u003Ch4>1. Generating JWT Tokens for Users\u003C\u002Fh4>\u003Cp>File: auth.go\u003C\u002Fp>\u003Cpre>\u003Ccode class=\"language-plaintext\">package auth\n\nimport (\n    \"time\"\n    \"github.com\u002Fdgrijalva\u002Fjwt-go\"\n)\n\nvar jwtKey = []byte(\"supersecretkey\")\n\ntype Claims struct {\n    Username string `json:\"username\"`\n    jwt.StandardClaims\n}\n\nfunc GenerateToken(username string) (string, error) {\n    expirationTime := time.Now().Add(1 * time.Hour)\n    claims := &amp;Claims{\n        Username: username,\n        StandardClaims: jwt.StandardClaims{\n            ExpiresAt: expirationTime.Unix(),\n        },\n    }\n    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)\n    return token.SignedString(jwtKey)\n}\u003C\u002Fcode>\u003C\u002Fpre>\u003Ch4>2. Validating JWT Token in the WebSocket Server\u003C\u002Fh4>\u003Cp>File: websocket_server.go\u003C\u002Fp>\u003Cpre>\u003Ccode class=\"language-plaintext\">package main\n\nimport (\n    \"fmt\"\n    \"github.com\u002Fdgrijalva\u002Fjwt-go\"\n    \"github.com\u002Fgorilla\u002Fwebsocket\"\n    \"net\u002Fhttp\"\n    \"strings\"\n)\n\nvar upgrader = websocket.Upgrader{\n    CheckOrigin: func(r *http.Request) bool { return true },\n}\n\nfunc authenticateToken(tokenString string) (*jwt.Token, error) {\n    return jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {\n        return []byte(\"supersecretkey\"), nil\n    })\n}\n\nfunc handleWebSocket(w http.ResponseWriter, r *http.Request) {\n    authHeader := r.Header.Get(\"Authorization\")\n    tokenString := strings.TrimPrefix(authHeader, \"Bearer \")\n    token, err := authenticateToken(tokenString)\n    if err != nil || !token.Valid {\n        http.Error(w, \"Unauthorized\", http.StatusUnauthorized)\n        return\n    }\n    conn, _ := upgrader.Upgrade(w, r, nil)\n    defer conn.Close()\n    fmt.Println(\"Client connected with valid token\")\n}\n\nfunc main() {\n    http.HandleFunc(\"\u002Fws\", handleWebSocket)\n    fmt.Println(\"WebSocket Server Running on Port 8080\")\n    http.ListenAndServe(\":8080\", nil)\n}\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch3>Connecting WebSocket Client with JWT Token\u003C\u002Fh3>\u003Cp>File: client.js\u003C\u002Fp>\u003Cpre>\u003Ccode class=\"language-plaintext\">const token = \"your_jwt_token_here\";\nconst socket = new WebSocket(\"ws:\u002F\u002Flocalhost:8080\u002Fws\", [\"Authorization\", `Bearer ${token}`]);\n\nsocket.onopen = () =&gt; {\n    console.log(\"Connected to WebSocket server\");\n};\n\nsocket.onmessage = (event) =&gt; {\n    console.log(\"Message from server:\", event.data);\n};\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch3>Challenge!\u003C\u002Fh3>\u003Cp>Try adding Role-Based Access Control (RBAC) to your chat system so that different user roles can perform different actions. For example, an Admin can delete messages, while regular users cannot.\u003C\u002Fp>\u003Chr>\u003Ch3>Next EP\u003C\u002Fh3>\u003Cp>In EP.37, we will create a chat room management system that allows users to join or create chat rooms! 🚀\u003C\u002Fp>","r8v4zgsahjuwpeb","","2026-03-04 08:51:18.546Z","Learn how to add User Authentication to your WebSocket Chat using JWT Tokens to control user access permissions and enhance the security of your chat system.",{"categoryId":16,"keywordIds":30,"langId":74},{"blogIds":17,"collectionId":18,"collectionName":19,"createBy":20,"created":21,"id":7,"image":22,"imageAlt":12,"imagePath":23,"label":24,"name":25,"priority":26,"publishDate":27,"scheduleDate":12,"status":28,"updateBy":20,"updated":29},[],"sclcatblg987654321","school_category_blog","oplnwslvnmx5axc","2026-03-04 08:33:53.210Z","59ty92ns80w_15oc1implw.png","https:\u002F\u002Ftwsme-r2.tumwebsme.com\u002Fsclcatblg987654321\u002Fwqxt7ag2gn7xcmk\u002F59ty92ns80w_15oc1implw.png",{"en":25,"th":25},"Golang The Series",1,"2026-03-16 04:39:38.440Z","Publish","2026-03-17 06:07:59.733Z",[31,38,42,47,51,56,60,65,69],{"collectionId":32,"collectionName":33,"createBy":12,"created":34,"id":35,"publishDate":36,"scheduleDate":12,"status":28,"title":37,"updateBy":12,"updated":34},"sclkey987654321","school_keyword","2026-03-04 08:51:15.678Z","x176qvmm4bfx32y","2025-03-18 02:45:32.333Z","Token-Based Authentication",{"collectionId":32,"collectionName":33,"createBy":12,"created":39,"id":40,"publishDate":36,"scheduleDate":12,"status":28,"title":41,"updateBy":12,"updated":39},"2026-03-04 08:51:15.982Z","zea0opz6nut6xyt","Chat Security",{"collectionId":32,"collectionName":33,"createBy":12,"created":43,"id":44,"publishDate":45,"scheduleDate":12,"status":28,"title":46,"updateBy":12,"updated":43},"2026-03-04 08:20:14.253Z","ah6lvy4x8qe08l5","2026-01-28 00:54:28.566Z","Golang",{"collectionId":32,"collectionName":33,"createBy":12,"created":48,"id":49,"publishDate":45,"scheduleDate":12,"status":28,"title":50,"updateBy":12,"updated":48},"2026-03-04 08:20:11.547Z","ey3puyme01a9bsw","Go",{"collectionId":32,"collectionName":33,"createBy":12,"created":52,"id":53,"publishDate":54,"scheduleDate":12,"status":28,"title":55,"updateBy":12,"updated":52},"2026-03-04 08:44:13.770Z","ij1u9pugpnctjvk","2026-02-24 02:34:26.075Z","WebSocket Security",{"collectionId":32,"collectionName":33,"createBy":12,"created":57,"id":58,"publishDate":36,"scheduleDate":12,"status":28,"title":59,"updateBy":12,"updated":57},"2026-03-04 08:51:16.224Z","72cusu8ff0jdht3","Secure WebSocket",{"collectionId":32,"collectionName":33,"createBy":12,"created":61,"id":62,"publishDate":63,"scheduleDate":12,"status":28,"title":64,"updateBy":12,"updated":61},"2026-03-04 08:51:16.632Z","gwruu2q4m5nfnka","2025-03-18 02:45:28.077Z","User Authentication",{"collectionId":32,"collectionName":33,"createBy":12,"created":66,"id":67,"publishDate":36,"scheduleDate":12,"status":28,"title":68,"updateBy":12,"updated":66},"2026-03-04 08:51:16.953Z","kjy1yv18jau2io3","JWT",{"collectionId":32,"collectionName":33,"createBy":12,"created":70,"id":71,"publishDate":72,"scheduleDate":12,"status":28,"title":73,"updateBy":12,"updated":70},"2026-03-04 08:44:42.406Z","julxx94rca568ku","2026-01-12 03:40:09.510Z","WebSocket Authentication",{"code":75,"collectionId":76,"collectionName":77,"createAt":78,"id":79,"is_default":80,"language":81,"updateAt":82},"en","pbc_1989393366","locale","2026-01-22 11:00:02.726Z","qv9c1llfov2d88z",false,"English","2026-02-05 10:48:59.032Z","9wnai6mz1o9mnhv","44_11zon_utad8d16wn.webp","EP. 36 Adding Authentication to WebSocket Chat","https:\u002F\u002Ftwsme-r2.tumwebsme.com\u002Fsclblg987654321\u002F9wnai6mz1o9mnhv\u002F44_11zon_utad8d16wn.webp",[35,40,44,49,53,58,62,67,71],"websocket-chat-authentication-jwt","2026-03-04 08:51:18.861Z",257,{"pagination":92},{"page":26,"pageSize":26,"pageCount":26,"total":26}]