-
Notifications
You must be signed in to change notification settings - Fork 208
Expand file tree
/
Copy pathmain.go
More file actions
91 lines (79 loc) · 2.49 KB
/
main.go
File metadata and controls
91 lines (79 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"log"
"net/http"
jwtmiddleware "github.com/auth0/go-jwt-middleware/v3"
"github.com/auth0/go-jwt-middleware/v3/validator"
"github.com/kataras/iris/v12"
)
// Try it out with:
//
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnby1qd3QtbWlkZGxld2FyZS1leGFtcGxlIiwiYXVkIjoiYXVkaWVuY2UtZXhhbXBsZSIsInN1YiI6IjEyMzQ1Njc4OTAiLCJuYW1lIjoiSm9obiBEb2UiLCJpYXQiOjE1MTYyMzkwMjIsInVzZXJuYW1lIjoidXNlcjEyMyJ9.XFhrzWzntyINkgoRt2mb8dES84dJcuOoORdzKfwUX70
//
// which is signed with 'secret' and has the data:
//
// {
// "iss": "go-jwt-middleware-example",
// "aud": "audience-example",
// "sub": "1234567890",
// "name": "John Doe",
// "iat": 1516239022,
// "username": "user123"
// }
//
// You can also try out the custom validation with:
//
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnby1qd3QtbWlkZGxld2FyZS1leGFtcGxlIiwiYXVkIjoiYXVkaWVuY2UtZXhhbXBsZSIsInN1YiI6IjEyMzQ1Njc4OTAiLCJuYW1lIjoiSm9obiBEb2UiLCJpYXQiOjE1MTYyMzkwMjIsInVzZXJuYW1lIjoidXNlcjEyMyIsInNob3VsZFJlamVjdCI6dHJ1ZX0.Jf13PY_Oyu2x3Gx1JQ0jXRiWaCOb5T2RbKOrTPBNHJA
//
// which is signed with 'secret' and has the data:
//
// {
// "iss": "go-jwt-middleware-example",
// "aud": "audience-example",
// "sub": "1234567890",
// "name": "John Doe",
// "iat": 1516239022,
// "username": "user123",
// "shouldReject": true
// }
func setupApp() *iris.Application {
app := iris.New()
app.Get("/api/public", func(ctx iris.Context) {
ctx.JSON(map[string]string{"message": "Hello from a public endpoint!"})
})
app.Get("/api/private", checkJWT(), func(ctx iris.Context) {
// Modern type-safe claims retrieval using generics
claims, err := jwtmiddleware.GetClaims[*validator.ValidatedClaims](ctx.Request().Context())
if err != nil {
ctx.StopWithJSON(
http.StatusInternalServerError,
map[string]string{"message": "Failed to get validated JWT claims."},
)
return
}
customClaims, ok := claims.CustomClaims.(*CustomClaims)
if !ok {
ctx.StopWithJSON(
http.StatusInternalServerError,
map[string]string{"message": "Failed to cast custom JWT claims to specific type."},
)
return
}
if len(customClaims.Username) == 0 {
ctx.StopWithJSON(
http.StatusBadRequest,
map[string]string{"message": "Username in JWT claims was empty."},
)
return
}
ctx.JSON(claims)
})
return app
}
func main() {
app := setupApp()
log.Print("Server listening on http://localhost:3000")
if err := app.Listen(":3000"); err != nil {
log.Fatalf("There was an error with the http server: %v", err)
}
}