MCPcopy Create free account
hub / github.com/kataras/iris / main

Function main

_examples/websocket/basic/server.go:46–126  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

44}
45
46func main() {
47 app := iris.New()
48 websocketServer := websocket.New(
49 websocket.DefaultGorillaUpgrader, /* DefaultGobwasUpgrader can be used too. */
50 serverEvents)
51
52 j := jwt.New(jwt.Config{
53 // Extract by the "token" url,
54 // so the client should dial with ws://localhost:8080/echo?token=$token
55 Extractor: jwt.FromParameter("token"),
56
57 ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
58 return []byte("My Secret"), nil
59 },
60
61 // When set, the middleware verifies that tokens are signed
62 // with the specific signing algorithm
63 // If the signing method is not constant the
64 // `Config.ValidationKeyGetter` callback field can be used
65 // to implement additional checks
66 // Important to avoid security issues described here:
67 // https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
68 SigningMethod: jwt.SigningMethodHS256,
69 })
70
71 idGen := func(ctx iris.Context) string {
72 if username := ctx.GetHeader("X-Username"); username != "" {
73 return username
74 }
75
76 return websocket.DefaultIDGenerator(ctx)
77 }
78
79 // serves the endpoint of ws://localhost:8080/echo
80 // with optional custom ID generator.
81 websocketRoute := app.Get("/echo", websocket.Handler(websocketServer, idGen))
82
83 if enableJWT {
84 // Register the jwt middleware (on handshake):
85 websocketRoute.Use(j.Serve)
86 // OR
87 //
88 // Check for token through the jwt middleware
89 // on websocket connection or on any event:
90 /* websocketServer.OnConnect = func(c *websocket.Conn) error {
91 ctx := websocket.GetContext(c)
92 if err := j.CheckJWT(ctx); err != nil {
93 // will send the above error on the client
94 // and will not allow it to connect to the websocket server at all.
95 return err
96 }
97
98 user := ctx.Values().Get("jwt").(*jwt.Token)
99 // or just: user := j.Get(ctx)
100
101 log.Printf("This is an authenticated request\n")
102 log.Printf("Claim content:")
103 log.Printf("%#+v\n", user.Claims)

Callers

nothing calls this directly

Calls 9

HandlerFunction · 0.92
NewMethod · 0.80
GetHeaderMethod · 0.80
ServeFileMethod · 0.80
WriteStringMethod · 0.80
GetMethod · 0.65
UseMethod · 0.65
HandleDirMethod · 0.65
ListenMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…