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
|
package main
import (
"fmt"
"log"
"net/http"
jwtmiddleware "github.com/auth0/go-jwt-middleware/v2"
"github.com/auth0/go-jwt-middleware/v2/validator"
"github.com/joho/godotenv"
"github.com/xlgmokha/api-auth0/pkg/middleware"
)
func main() {
if err := godotenv.Load(); err != nil {
log.Fatal(err)
}
router := http.NewServeMux()
router.Handle("/api/public", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"message":"public"}`))
}))
router.Handle("/api/private", middleware.EnsureValidToken()(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("in /api/private handler\n")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Authorization")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"message":"private"}`))
}),
))
router.Handle("/api/private-scoped", middleware.EnsureValidToken()(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Authorization")
w.Header().Set("Content-Type", "application/json")
token := r.Context().Value(jwtmiddleware.ContextKey{}).(*validator.ValidatedClaims)
claims := token.CustomClaims.(*middleware.CustomClaims)
if !claims.HasScope("read:messages") {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte(`{"message":"insufficient scope."}`))
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"message":"private-scoped"}`))
}),
))
log.Fatal(http.ListenAndServe("localhost:3000", router))
}
|