Debian Codegraph @

example/client/api/api.go

raw
1 package main
2
3 import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "log/slog"
8 "net/http"
9 "os"
10 "strings"
11 "time"
12
13 "github.com/go-chi/chi/v5"
14
15 "github.com/zitadel/oidc/v3/pkg/client/rs"
16 "github.com/zitadel/oidc/v3/pkg/oidc"
17 )
18
19 const (
20 publicURL string = "/public"
21 protectedURL string = "/protected"
22 protectedClaimURL string = "/protected/{claim}/{value}"
23 )
24
25 func main() {
26 keyPath := os.Getenv("KEY")
27 port := os.Getenv("PORT")
28 issuer := os.Getenv("ISSUER")
29
30 provider, err := rs.NewResourceServerFromKeyFile(context.TODO(), issuer, keyPath)
31 if err != nil {
32 slog.Error("error creating provider", "error", err)
33 os.Exit(1)
34 }
35
36 router := chi.NewRouter()
37
38 // public url accessible without any authorization
39 // will print `OK` and current timestamp
40 router.HandleFunc(publicURL, func(w http.ResponseWriter, r *http.Request) {
41 w.Write([]byte("OK " + time.Now().String()))
42 })
43
44 // protected url which needs an active token
45 // will print the result of the introspection endpoint on success
46 router.HandleFunc(protectedURL, func(w http.ResponseWriter, r *http.Request) {
47 ok, token := checkToken(w, r)
48 if !ok {
49 return
50 }
51 resp, err := rs.Introspect[*oidc.IntrospectionResponse](r.Context(), provider, token)
52 if err != nil {
53 http.Error(w, err.Error(), http.StatusForbidden)
54 return
55 }
56 data, err := json.Marshal(resp)
57 if err != nil {
58 http.Error(w, err.Error(), http.StatusInternalServerError)
59 return
60 }
61 w.Write(data)
62 })
63
64 // protected url which needs an active token and checks if the response of the introspect endpoint
65 // contains a requested claim with the required (string) value
66 // e.g. /protected/username/[email protected]
67 router.HandleFunc(protectedClaimURL, func(w http.ResponseWriter, r *http.Request) {
68 ok, token := checkToken(w, r)
69 if !ok {
70 return
71 }
72 resp, err := rs.Introspect[*oidc.IntrospectionResponse](r.Context(), provider, token)
73 if err != nil {
74 http.Error(w, err.Error(), http.StatusForbidden)
75 return
76 }
77 requestedClaim := chi.URLParam(r, "claim")
78 requestedValue := chi.URLParam(r, "value")
79
80 value, ok := resp.Claims[requestedClaim].(string)
81 if !ok || value == "" || value != requestedValue {
82 http.Error(w, "claim does not match", http.StatusForbidden)
83 return
84 }
85 w.Write([]byte("authorized with value " + value))
86 })
87
88 lis := fmt.Sprintf("127.0.0.1:%s", port)
89 slog.Info("listening", "url", "http://"+lis+"/")
90 if err := http.ListenAndServe(lis, router); err != nil {
91 slog.Error("server terminated", "error", err)
92 os.Exit(1)
93 }
94 }
95
96 func checkToken(w http.ResponseWriter, r *http.Request) (bool, string) {
97 auth := r.Header.Get("authorization")
98 if auth == "" {
99 http.Error(w, "auth header missing", http.StatusUnauthorized)
100 return false, ""
101 }
102 if !strings.HasPrefix(auth, oidc.PrefixBearer) {
103 http.Error(w, "invalid header", http.StatusUnauthorized)
104 return false, ""
105 }
106 return true, strings.TrimPrefix(auth, oidc.PrefixBearer)
107 }