forked from zetane/ZetaForge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken.go
76 lines (65 loc) · 1.65 KB
/
token.go
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
package main
import (
"crypto"
"errors"
"log"
"net/http"
"os"
"path/filepath"
"strings"
jwt "github.com/golang-jwt/jwt/v5"
)
func loadCertificates(folder string) (map[string]crypto.PublicKey, error) {
certificates := make(map[string]crypto.PublicKey)
files, err := os.ReadDir(folder)
if err != nil {
return certificates, err
}
for _, file := range files {
name := file.Name()
pemRaw, err := os.ReadFile(filepath.Join(folder, name))
if err != nil {
log.Printf("Could not read cert; err=%v", err)
continue
}
ecdsaKey, err := jwt.ParseEdPublicKeyFromPEM(pemRaw)
if err != nil {
log.Printf("Could not parse public key; err=%v", err)
continue
}
certificates[strings.TrimSuffix(name, filepath.Ext(name))] = ecdsaKey
}
return certificates, nil
}
func validateToken(bearer string, folder string) (int, string) {
certs, err := loadCertificates(folder)
if err != nil {
log.Printf("Could not load certificates")
return http.StatusUnauthorized, ""
}
if len(strings.Fields(bearer)) != 2 {
log.Printf("Invalid authorization header")
return http.StatusUnauthorized, ""
}
token, err := jwt.Parse(strings.Fields(bearer)[1], func(t *jwt.Token) (interface{}, error) {
sub, err := t.Claims.GetSubject()
if err != nil {
return "", err
}
key, ok := certs[sub]
if !ok {
return "", errors.New("Subject certificate missing")
}
return key, nil
}, jwt.WithValidMethods([]string{"EdDSA"}))
if err != nil {
log.Printf(err.Error())
return http.StatusUnauthorized, ""
}
if !token.Valid {
log.Printf("Invalid token")
return http.StatusUnauthorized, ""
}
sub, _ := token.Claims.GetSubject()
return http.StatusOK, sub
}